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  

  • Similar Content

    • By nacerbaaziz
      hello sirs
      i've some questions about StringRegExpReplace i hope you can help me
       
      i tried to make a function that give me the host of the url and other give me the url with out host
      for example i've this link
      https://www.example.com/vb/result.php
      i need the first give me the
      example.com
      and the other give me 
      /vb/result.php
      i find that
      $s_source = "https://www.google.com/vb/index.php" Local $s_Host = StringRegExpReplace($s_Source, '.*://(.*?)/.*', '\1') Local $s_Page = StringRegExpReplace($s_source, '.*://.*?(/.*)', '\1') msgBox(64, $s_Host, $s_Page)  
      but i found some problems i need your help to correct it
      first: when i get the host if the url has www i want to remove it
      second: if the url with out host did not have other things 
      i need the result to be ""
      e.g
      https://www.example.com
      the first i want it
      example.com
      and the second i want it to be ""
      i hope that you can help me
      thanks in advance
    • By fs1234
      Hi,
      I would like to change the hungarian characters in a string, but I can't figure out how to do it.
      Help, pls.
       
      #include <MsgBoxConstants.au3> Local $sInput = "Árvíztűrő tükörfúrógép" Local $sOutput = StringRegExpReplace($sInput, "(?-i)(á)|(Á)|(é)|(É)|(í)|(Í)|(ó)|(Ó)|(ö)|(Ö)|(ő)|(Ő)|(ú)|(Ú)|(ü)|(Ü)|(ű)|(Ű)", "(?1a)(?2A)(?3e)(?4E)(?5i)(?6I)(?7o)(?8O)(?9o)(?10O)(?11o)(?12O)(?13u)(?14U)(?15u)(?16U)(?17u)(?18U)") Display($sInput, $sOutput) Func Display($sInput, $sOutput) ; Format the output. Local $sMsg = StringFormat("Input:\t%s\n\nOutput:\t%s", $sInput, $sOutput) MsgBox($MB_SYSTEMMODAL, "Results", $sMsg) EndFunc ;==>Display  
    • By Skysnake
      I need some regex help
      I inherited some data 
      The data is massive and I need a clean, fast solution 
      source is text and complex.  
      I need to find dates such as "31-01-2018" and replace with "31-JAN-2018"
      Problem is that my regex "31-01-2018" takes for ever and replaces all.
      The ideal would be to search like this, but I am not managing
      \d{2}-(01)-\d{4} replace (01) with JAN But if I do it that way, the entire search string gets replaced by JAN.  This is not an error, but typically regex behaviour.  Any ideas?
      Skysnake
    • By therks
      So I have this pattern: 
      ^(?:(\d+)|(\d+):(\d+)|(\d+):(\d+):(\d+))$ And I'm expecting (depending on input) to get a 1, 2 or 3 index array (or @error for invalid input).
      But instead I get this:
      #include <Debug.au3> Func Test($String) _DebugArrayDisplay(StringRegExp($String, '^(?:(\d+)|(\d+):(\d+)|(\d+):(\d+):(\d+))$', 1)) EndFunc Test('10') ; Results (normal, expected): ; Row 0|10 Test('10:20') ; Results (extra blank index): ; Row 0| ; Row 1|10 ; Row 2|20 Test('10:20:30') ; Results (three blank indices): ; Row 0| ; Row 1| ; Row 2| ; Row 3|10 ; Row 4|20 ; Row 5|30 Is this normal? Should I just code around it, or is there a better way to do what I'm looking for?
      I also tried reversing my regex, but it was even uglier results:
      #include <Debug.au3> Func Test($String) _DebugArrayDisplay(StringRegExp($String, '^(?:(\d+):(\d+):(\d+))|(\d+):(\d+)|(\d+)$', 1)) EndFunc Test('10') ; Results (yuck): ; Row 0| ; Row 1| ; Row 2| ; Row 3| ; Row 4| ; Row 5|10 Test('10:20') ; Results (slightly better): ; Row 0| ; Row 1| ; Row 2| ; Row 3|10 ; Row 4|20 Test('10:20:30') ; Results (nice): ; Row 0|10 ; Row 1|20 ; Row 2|30  
    • By Deye
      Hi,
      I want to add any needed conditions to the StringRegExp command so it can pull out only  "File.au3", "WinAPIFiles.au3", "Test.bmp" into the array
      #include <FileConstants.au3> #include <MsgBoxConstants.au3> #include 'WinAPIFiles.au3' #include "File.au3" ; Script Start - Add your code below here Local $bFileInstall = False ; Change to True and ammend the file paths accordingly. ; This will install the file C:\Test.bmp to the script location. If $bFileInstall Then FileInstall("C:\Test.bmp", @ScriptDir & "\Test.bmp") $sFile = FileRead(@ScriptFullPath) $aResults = StringRegExp($sFile, "(?i)(FileInstall\s*|include\s*)(.*)", 3) _ArrayDisplay($aResults) Thanks In Advance
      Deye
×
×
  • Create New...