Jump to content
Sign in to follow this  
qwert

Request for help formulating regular expression

Recommended Posts

I’m a complete newbie when it comes to using StringRegExp. Although I’ve successfully modified a couple of patterns in existing scripts, I’ve never been sure where to start in formulating a new pattern. Thus, I’ve avoided using them. But now I need to.

 

The string I’d like to recognize and replace is of the form:

 

prekeykey<any characters>post

 

To put it in words, I’m looking for any occurrence of two or more consecutive key strings that are embraced by pre and post strings, regardless of any follow-on characters. The slash characters are part of the individual elements, but could possibly occur on their own. (What makes this doubly confusing is that the slash character is an element of the RegExp syntax.)

 

Examples of strings to be recognized and replaced:

prekeykeykeykey post

prekeykeykeykeyabcdpost

prekeykeypost

 

But neither of the following should be “found”, since the have only one key:

prekeypost

prekeyabcdpost

 

If someone versed in RegExp’s would be so kind as to provide me with a nudge in the form of a suitable pattern, I might be able to make my way further along the path toward a working knowledge of these things. So far, I’ve looked at 100 examples and can’t get a toehold.  Detecting "two consecutive" appears to be a rare requirement.

 

Thanks in advance for any help.

Share this post


Link to post
Share on other sites

Something like this could do the job :

If StringRegExp($string, "^\\pre(\\key){2,}.*?\\post$") Then
    ConsoleWrite("Match")
Else
    ConsoleWrite("Not match")
EndIf

^                 starts with
pre           pre
(key){2,}   key two or more time
.*?              something or not, till next item
post         post
$                ends with

Share this post


Link to post
Share on other sites

qwert,

This seems to work: :)

Global $aTest[5] = ["\pre\key\key\key\key\ \post", _
"\pre\key\key\key\keyabcd\post", _
"\pre\key\key\post", _
"\pre\key\post", _
"\pre\keyabcd\post"]

For $i = 0 To 4
    ConsoleWrite($aTest[$i] & " - " & StringRegExpReplace($aTest[$i], "(?U)^(\\pre.*)(\\)(key.*)(\g2)(\g3)(\g2)(.*)$", "$1\\FRED\\FRED\\$7") & @CRLF)
Next
SRE decode:

(?U)      - Not greedy so as few characters as possible
^         - Start of string
(\\pre.*) - Capture "\pre" and any characters up to \ (save as group 1)
(\\)      - Capture a backslash - save as Group 2
(key.*)   - Capture key followed by any characters (save as Group 3) until we meet
(\g1)     - Another group 2 followed by
(\g2)     - Another group 3 and
(\g1)     - yet another group 2
(.*)      - Capture all (save as group 7) until
$         - end of string

Replace with
$1        - Group 1
\\FRED\\FRED\\ ; The replacement for the found double key
$7        - Group 7
This is the first time I have used backreferenced groups - seems quite a powerful thing to have in the armoury. :graduated:

M23

Edited by Melba23
Realised it was SRER and not SRE

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

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Share this post


Link to post
Share on other sites

My 2 cents  :D

This one allows special characters in the test substring

Global $aTest[6] = ["\pre\key\key\key\key\ \post", _
        "\pre\key\key\key\keyabcd\post", _
        "\pre\key\key\post", _
        "\pre\key\keyabcd\post", _
        "\pre\key\post", _
        "\pre\keyabcd\post"]

$test = "key"
For $i = 0 To 5
  ConsoleWrite(StringRegExp($aTest[$i], '((?<=\\)\Q' & $test & '\E.*?\\){2,}') & " - " & $aTest[$i] & @CRLF)
Next

Q...E  for possible special characters

(?<=)  preceded by a

{2,}  2 or more times

Edit

Melba, :thumbsup:

But it will fail on "prekeykeyabcdpost" because the content of the backref is not the same

Though I don't know if "prekeyabkeycdpost" should be matched or not

My code matches this, but if it shouldn't just remove the .*?

Edited by mikell

Share this post


Link to post
Share on other sites

I see people at work here.


This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Share this post


Link to post
Share on other sites

Some short feedback (as I have more testing to do):

I have "^pre(key){2,}.*?post$" working for my simplest case (the one I described).  I dropped the $ ("ends with") because there can be other characters after the post element, which I didn't mention. 

I'll look at each method in detail over the next couple of days.  Already, I'm optimistic that these will give me pretty good starting points for other uses. 

Thanks to each of you for the responses.


Share this post


Link to post
Share on other sites

mikell,

 

it will fail on "prekeykeyabcdpost"

The OP's requirements were not altogether clear, but I assumed that the successive keys needed to be identical. Perhaps the OP could tell us so we can modify our respective patterns. :)

M23


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

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Share this post


Link to post
Share on other sites

Here are a few more guesses of what your required return strings is supposed to be.

Maybe giving an example input text together with an example of the expected output in the opening post would have been helpful to the helpers.

Global $sTest = "In between \pre\key\key\key\key\ \post some text" & @CRLF & _
        "\pre\key\key\key\keyabcd\post" & @CRLF & _
        "\pre\key\key\post" & @CRLF & _
        "\pre\key\post" & @CRLF & _
        "\pre\keyabcd\post"

ConsoleWrite(StringRegExpReplace($sTest, "(\\pre.*?)(\\key[^\\]*)\2+(.*?\\post)", "$1\\FRED\\FRED$3") & @CRLF)
#cs Returns:-
    In between \pre\FRED\FRED\ \post some text
    \pre\FRED\FREDabcd\post
    \pre\FRED\FRED\post
    \pre\key\post
    \pre\keyabcd\post
#ce

ConsoleWrite(@CRLF & " ------ " & @CRLF & StringRegExpReplace($sTest, "(\\pre.*?\\)(key\\)\2+(.*?\\?post)", "$1FRED\\FRED\\$3") & @CRLF & @CRLF)
#cs Returns:-
    In between \pre\FRED\FRED\ \post some text
    \pre\FRED\FRED\keyabcd\post
    \pre\FRED\FRED\post
    \pre\key\post
    \pre\keyabcd\post
#ce

; Post#1: The string I’d like to recognize and replace is of the form: "\pre\key\key<any characters>\post"
ConsoleWrite(@CRLF & " ------ " & @CRLF & StringRegExpReplace($sTest, "(\\pre.*?)(\\key[^\\]*)\2+(.*?\\post)", "\\FRED\\FRED") & @CRLF)
#cs Returns:-
    In between \FRED\FRED some text
    \FRED\FRED
    \FRED\FRED
    \pre\key\post
    \pre\keyabcd\post
#ce

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 ni3dprint
      Hi folks, 
      Thank you so much in advance for your help!  I've been using AUTOIT for manipulating gcode.  So far I've just worked through the excellent help examples and although I'm sure the resulting code is clumsy it has functioned  
      However now I'm trying to improve and advance things and I've stumbled across REGEX.. and I'm a bit stuck.  What I would like to be able to do is to 'move'/'transform' the gcode in a file and re-write it to a new file.  I only need to move it in one direction(X).  At the heart of this I need a script to extract all the X values and then ADD or SUBTRACT an adjustment factor to transform and rewrite the code accordingly.
      So far using an example script and an example input -
      Func Test2()
      Local $iMove = -4
          Local $sInput = '"G1 X45.036 Y6.934 F7800.000 G1 Z0.600 F7800.000 G1 F900 G1 X48.036 Y1.076 E0.58925"'
          Local $sOutput = StringRegExpReplace($sInput, '(?<=[X])\d+.\d+', '\0')
          Display($sInput, $sOutput)
      EndFunc   ;==>Test2
      This identifies the correct values i.e 45.036 and 48.036 but is there a way to dyamically adjust them before they are replaced, by for example a factor of -4 ($iMove above).  So far I can't seem to do math on the '\0' value i.e '\0'+ -4 ?
      Many thanks for your time and expertise!
       
    • 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  
    • By jmp
      I am adding labour charge to total paid amount using : 
      #include <IE.au3> #include <Array.au3> $oIE = _IEAttach ("Shop") $oTable = _IETableGetCollection ($oIE, 1) $aTableData3 = _IETableWriteToArray ($oTable) Local $sitem1 = $aTableData3[5][1] Local $sitem2 = $aTableData3[5][2] Local $lcharge = "10" ;add manualy using inputbox, becuase not generating online Local $atotPric = "Payable Total Price " Local $oTds = _IETagNameGetCollection($oIE, "td") For $oTd In $oTds If $oTd.Innertext = $atotPric Then $iatotPric = $oTd.NextElementSibling.innertext MsgBox (0, "2", $iatotPric) EndIf Next $irCtotal = StringFormat("%.2f", $sitem1 + $sitem2 + $lcharge) $crTotp = StringReplace(_IEBodyReadHTML($oIE), $iatotPric, $irCtotal) _IEBodyWriteHTML ($oIE, $crTotp) But, It was also changing Total price, I want to change only Payable Total Price.

×
×
  • Create New...