Jump to content
Sign in to follow this  
WoodGrain

StringRegExpReplace - replace 'COMMA' with ','

Recommended Posts

Hi All,

I'd like to replace 'COMMA' with ',' for example:

$myString = "COMMA"
StringRegExpReplace($myString, 'COMMA', ',')

Now I've tried escaping the ',' in various ways unsuccessfully, such as:
'[,]'
"[,]"
'\,'

[,] seems to work in the pattern, I just can't figure out how to use it in the replace, and it seems everyone online is only interested in removing/replacing commas lol.

I also tried creating and using a variable as the replacement but also didn't work:

$myComma = ","
$myString = "COMMA"
StringRegExpReplace($myString, 'COMMA', $myComma)

I'm sure it's super simple if someone could point me in the right direction - thanks.

Share this post


Link to post
Share on other sites

Hi.

This works for me:

Local $sMyString = "HelloCOMMA this is a testCOMMA if Comma will be replaced."
Local $sReplacedString = StringRegExpReplace($sMyString, 'COMMA', ',')
ConsoleWrite($sReplacedString & @CRLF)

Regards, Conrad


SciTE4AutoIt = 3.7.3.0   AutoIt = 3.3.14.2   AutoItX64 = 0   OS = Win7Pro SP1   OSArch = X64   Language = 0407/german
H:\...\AutoIt3\SciTE     H:\...\AutoIt3      H:\...\AutoIt3\Include     (H:\ = Network Drive)

   88x31.png  Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind.

Share this post


Link to post
Share on other sites

Thanks guys for your replies, I've realised my issue is not in the replacement, it's later when I split out the string into an array... it's actually working which is why I'm getting empty elements. So I'll have to fix this by changing the separator value.

Thanks again guys for clarifying it's not the escaping that's the issue.

Share this post


Link to post
Share on other sites

Can you provide an accurate reproducer of just what you are starting with, and what you want it to look like in the end. 

If the ultimate issue is a split leaving empty elements, and we have easily identifiable characters to split on, then regex may be unnecessary.  (e.g. things like stringsplit can split on entire substrings). 

#include<array.au3>

$myString = "SomeTextCOMMAMoarTextCOMMAThisCSVisWeirdCOMMAEndOfText"

_ArrayDisplay(stringsplit($myString , "COMMA" , 3))

 


,-. .--. ________ .-. .-. ,---. ,-. .-. .-. .-.
|(| / /\ \ |\ /| |__ __||| | | || .-' | |/ / \ \_/ )/
(_) / /__\ \ |(\ / | )| | | `-' | | `-. | | / __ \ (_)
| | | __ | (_)\/ | (_) | | .-. | | .-' | | \ |__| ) (
| | | | |)| | \ / | | | | | |)| | `--. | |) \ | |
`-' |_| (_) | |\/| | `-' /( (_)/( __.' |((_)-' /(_|
'-' '-' (__) (__) (_) (__)

Share this post


Link to post
Share on other sites

All good thanks @iamtheky, I need to split using a "," as the delimiter for everything else. I walk through the array after my StringRegExpReplace to make a 2D array anyway, so I just ran an IF statement while walking through the array to replace any instance of COMMA with an actual ",". Cheers.

Share this post


Link to post
Share on other sites

Here's a follow on question though, when I am walking through the array, would it be more efficient to (assuming < 10 instances of "COMMA" in the array):

  1. Use StringInStr on each array element and if it finds "COMMA" in the element to then do a StringRegExReplace (this is what I'm currently doing), or
  2. Just run a StringRegExReplace on every element

It's neither here nor there in this case as the 2D array has less than 1,000 elements anyway, but I'm interested in the concept.

Share this post


Link to post
Share on other sites

I'm sure you will reach a threshold between 'total elements searched -vs- how many matches' where you could optimize.  You could _arraytostring and then just run a single regular expression, dont know if it beats a loop though.

Or you could grab only the matching elements out of the array first with UDFs that are already optimized, then act only on the matches with native functions.  That usually ends up cleaner and quicker.

#include<array.au3>

local $arr = ["SomeTextCOMMA" , "MoarTextCOMMA" , "TextAboutASitcomMaybe" , "AndAnotherCOMMA" , "EndOfText"]

$found = _ArrayFindAll($arr , "COMMA" , 0 , 0 , 1 , 1)

For $i = 0 to ubound($found) - 1
    $arr[$found[$i]] = stringreplace($arr[$found[$i]] , "COMMA" , ",")
Next

_ArrayDisplay($arr)

 

Edited by iamtheky

,-. .--. ________ .-. .-. ,---. ,-. .-. .-. .-.
|(| / /\ \ |\ /| |__ __||| | | || .-' | |/ / \ \_/ )/
(_) / /__\ \ |(\ / | )| | | `-' | | `-. | | / __ \ (_)
| | | __ | (_)\/ | (_) | | .-. | | .-' | | \ |__| ) (
| | | | |)| | \ / | | | | | |)| | `--. | |) \ | |
`-' |_| (_) | |\/| | `-' /( (_)/( __.' |((_)-' /(_|
'-' '-' (__) (__) (_) (__)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By Colduction
      Hi guys!, i have a problem to convert Python code to AutoIt code, in fact i had not coded with Python yet!, this code is about permutation a string's case, i will be happy with your comments :)❤;

      Python code:
       
      # Python code to print all permutations # with respect to cases # Function to generate permutations def permute(inp): n = len(inp) # Number of permutations is 2^n mx = 1 << n # Converting string to lower case inp = inp.lower() # Using all subsequences and permuting them for i in range(mx): # If j-th bit is set, we convert it to upper case combination = [k for k in inp] for j in range(n): if (((i >> j) & 1) == 1): combination[j] = inp[j].upper() temp = "" # Printing current combination for i in combination: temp += i print(temp), # Driver code permute("Hello") # This code is contributed by Sachin Bisht
      My code in AutoIt:
      ; https://www.geeksforgeeks.org/permute-string-changing-case/ _PermuteCase("ABC") Func _PermuteCase($sText) If StringRegExp($sText, "^[A-Za-z]{1,}$") Then Local $iLength = StringLen($sText) ; Get length of the text. Local $iMaxPerm = 2 ^ $iLength ; Number of permutations is 2^n Local $sLow_Text = StringLower($sText) ; Converting string to lower case Local $asChrs = StringToASCIIArray($sLow_Text) ; Split the text into array of chars. For $i = 1 To $iMaxPerm Step 1 For $j = 0 To $asChrs[0] ;................................................... Next Next Else Return SetError(-1, 0, "Error: Input is incorrect!") EndIf EndFunc ;==>_PermuteCase  
       
       
       
       
       
      ====================== SOLUTION by @TheXman ======================
       
    • By careca
      This is another take on string triggers, triggers on specific strings.
      Able to simple text pasting,
      opening links (as long as there's a www. http:\\ or https:\\ at the beggining)
      and is able to open applications, if there is a parameter in the parameter field, it uses it.
      Shows your external, lan, and gateway ip's.
      Able to change system volume by a set percentage, reading from the inputbox the number the user sets, if 0 or empty uses system default.
      The 4 longer input fields at the bottom, represent the process scaning, the 2 to the left continuously scan for the process name,
      and the 2 to the right are executed when the process in the left is found.
      process 1 for app 1, example, look for notepad.exe and start paint.exe if notepad is found.
      I made this because the existing string trigger applications didn't do it for me.
      I did this for me, but if someone finds it useful all the better.
    • By genius257
      Inspired by PHP's preg_split.
      Split string by a regular expression.
      Also supports the same flags as the PHP equivalent.
      v1.0.1
       
      Example:
      #include "StringRegExpSplit.au3" StringRegExpSplit('splitCamelCaseWords', '(?<=\w)(?=[A-Z])') ; ['split', 'Camel', 'Case', 'Words']  
    • By jmp
      i am trying to get number from string using this code :
      #include <IE.au3> $oIE = _IEAttach ("Edu.corner") Local $aName = "Student name & Code:", $iaName = "0" Local $oTds = _IETagNameGetCollection($oIE, "td") For $oTd In $oTds If $oTd.InnerText = $aName Then $iaName = $oTd.NextElementSibling.InnerText $iGet = StringRegExpReplace($iaName, "\D", "") EndIf Next MsgBox(0, "", $iGet) it was get number like 52503058
      But, I want to get only student code 5250. (Different student have different code, sometime its 3 digits, Sometime 4)

       
    • By BlueBandana
      Is there a way to output the regex matches into a file?
      I have a script to compare two files and check for regex matches.
      I want to output the matching regex of 'testexample.txt' to another file.
      #include <MsgBoxConstants.au3> #include <Array.au3> $Read = FileReadToArray("C:\Users\admin\Documents\testexample.txt") $Dictionary = FileReadToArray("C:\Users\admin\Documents\example.txt") For $p = 0 To UBound($Dictionary) - 1 Step 1 $pattern = $Dictionary[$p] For $i = 0 To UBound($Read) - 1 Step 1 $regex = $Read[$i] If StringRegExp($regex, $pattern, 0) Then MsgBox(0, "ResultsPass", "The string is in the file, highlighted strings: " ) Else MsgBox(0, "ResultsFail", "The string isn't in the file.") EndIf Next Next  
×
×
  • Create New...