Jump to content

Smart RegEx - MultiPattern


Recommended Posts

Hello ,
can you please advise a regex to handle any of the following

 

Input :
" march30 ,2013"
"March 30 ,2013"
"March 30, 2013"
"March 30, 2013 "
"March30 ,2013"
" March 6 , 2013 "
" March8,2013"
etc

Basically all imaginable combinations of lowercase-uppercase , position-of-space , number-of-spaces , position-of-comma , comma-can-be-dot sometimes.
So it should read within quotes , search for word "march" (in any case) two|one digit occurrence together would be the date , 4 digit together would be year.


Output Consistent :
|"March 3, 2013"|



This works , however , there will be too many combinations to do,
 

$line_read = StringRegExpReplace($line_read, '["]March((\d{1})|(\d{2}))[,][\h](\d{4})["]', '|March $1, $4|')

A slightly advanced ask would be to also use similarity , function from here :
https://www.autoitscript.com/forum/topic/40843-calculate-string-similarity/

to check for close spellings to march and finally output as a consistent "march".


Side Question 1 : 
Simplest method to return the position of occurence of regex.
This works , but how to search from right.
 

Local $string = "abcdefghijklmn555opqrstuvmxyz"

MsgBox(0, "", _StringPos($string, "\d\d\d") )

Func _StringPos($sString, $sSearch)
    StringRegExp($string, "(?=" & $sSearch & ")", 1)
    Return @error ? 0 : @extended
EndFunc

 

Link to comment
Share on other sites

When it comes to really complex regex, first thing I'd do is strip out as many variables as I can.

Examples:

  • StringStripWS($line_read, $STR_STRIPALL) to remove having to deal with whitespace
  • StringReplace($line_read, ".", ",") to remove any chance of a period being used
  • StringLower($line_read) OR StringUpper($line_read) to remove having to deal with both upper and lower case

Once all that is done then do your regex

 

My UDFs are generally for me. If they aren't updated for a while, it means I'm not using them myself. As soon as I start using them again, they'll get updated.

My Projects

WhyNotWin11
Cisco FinesseGithubIRC UDFWindowEx UDF

 

Link to comment
Share on other sites

  • Moderators

adityaparakh,

This seems to work quite well on your examples:

#include <Array.au3>

Global $aDates[] = [" march30 ,2013", _
                    "March 30 ,2013", _
                    "March 30, 2013", _
                    "March 30, 2013 ", _
                    "March30 ,2013", _
                    " March 6 , 2013 ", _
                    " March8,2013"]

For $i = 0 To UBound($aDates) - 1

    $aDates[$i] = StringRegExpReplace($aDates[$i], "(?iU)^.*(march).*(\d{1,2}?).*[\,\.].*(\d\d\d\d).*$", "$1 $2, $3")

Next

_ArrayDisplay($aDates, "", Default, 8)
(?iU)         case insensitive and greedy
^.*           start at the beginning of the string
(march)       capture "march"
.*            possible characters until
(\d{1,2}?)    capture either one or 2 digits
.*            possible characters
[\,\.]        but at least a comma or period
.*            possible characters
(\d\d\d\d)    capture 4 digits
.*$           possible characters util the end of the string

$1 $2, $3     write the captured groups in the required format

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

Try this one :

Local $aString = [" march30 ,2013", _
                    "March 30 ,2013", _
                    "March 30, 2013", _
                    "March 30, 2013 ", _
                    "March30 ,2013", _
                    " March 6 , 2013 ", _
                    " March8,2013"]

For $i = 0 To UBound($aString) - 1
    $date = StringRegExpReplace($aString[$i], "(?i)\s*march\s*(\d\d?)\s*.\s*(\d{4})\s*", "|""March $1, $2""|")
    ConsoleWrite($date & @CRLF)
Next

 

Link to comment
Share on other sites

About typing errors you can benefit reading this:

 

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

Here is another example, where the function _FormatDates() reformats one or more dates in a string.

#cs
" january30 ,2013"
"February 28 ,2014"
"March 27, 2015"
"april 26, 2016 "
"May 5 ,2017"
" June6 , 2018 "
" july8,2019"
#ce

Global $sDates = StringRegExpReplace(FileRead(@ScriptFullPath), "(?s)^.*?#cs\v+|\v+#ce.*", "")
ConsoleWrite(_FormatDates($sDates) & @CRLF)

Func _FormatDates($sString) ; Month dd, YYYY
    Local $a = StringRegExp($sString, '(?i)"\h*([a-z]+)\h*(\d{1,2})\h*[\,\.]?\h*(\d{4})\h*"', 3)
    Local $sRet
    For $i = 0 To UBound($a) - 1 Step 3
        $sRet &= StringUpper(StringLeft($a[$i], 1)) & StringTrimLeft($a[$i], 1) & " " & StringRight("00" & $a[$i + 1], 2) & ", " & $a[$i + 2] & @CRLF
    Next
    Return StringTrimRight($sRet, 2) ; Remove trailing @CRLF
EndFunc   ;==>_FormatDates

 

Edited by Malkey
Link to comment
Share on other sites

And another one...  :)

$string = " jaNuary30 ,2013  "

$res = '|"' & Execute(StringRegExpReplace($string, _ 
        '\h*(\w)([[:alpha:]]+)\h*(\d+)\h*[,.]\h*(\d{4})\h*', _ 
        "StringUpper('$1') & StringLower('$2') & ' $3, $4' & ") & "''") & '"|'

Msgbox(0,"", $res)

 

Edit for side question

Local $string = "abcdefa555gh"

MsgBox(0, "", _StringPos($string, "\d\d\d") )

Func _StringPos($sString, $sSearch)
    StringRegExp($string, "(?=" & $sSearch & ")", 1)
    $pos1 = @error ? 0 : @extended
    Return StringLen($sString)-$pos1+1
EndFunc

 

Edited by mikell
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

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...