Jump to content

Request for help formulating regular expression


qwert
 Share

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.

Link to comment
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

Link to comment
Share on other sites

  • Moderators

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

 

Link to comment
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
Link to comment
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)

Link to comment
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.


Link to comment
Share on other sites

  • Moderators

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

 

Link to comment
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
Link to comment
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
 Share

×
×
  • Create New...