Core Function Regex Match
<Expression> =~ m/pattern/flags
Contents |
Description
Match a string to a regular expression pattern and check if it matches and optionally return captured groups
Parameters
Expression
Any valid expression that is a string.
pattern
The regular expression pattern to match.
flags
Optional; The flags to use in the pattern.
i = Ignore case.
m = Treat the string as multiple lines.
s = Treat the string as a single line.
o = Do not recompile the regular expression after the first compile (Improves speed of your matches if you run the pattern many times).
g = Match all occurrences of the pattern in the string (Default is only match the first).
d = Return a single dimension array when using flag "g" (Default is to return a multidimensional array).
x = Allows newlines and commands and ignores whitespace in the regex
Note - If flag "g" is used the $_rg array will contain all matches from first to last it will not contain the text it matched it will only contain the matches, However if "g" is not used then the first element will be the matched text followed by all the matched groups 1 2 3 4 etc.
Return Value
Success: Returns 1 if the match was successful.
Failure: Returns 0.
Remarks
Note - The below is only for single matches not flag "g" matches.
If a regular expression pattern is matched correctly and it has capture groups in the pattern the groups will be set to local variables for example:
Group 0 will be $0.
Group 1 will be $1.
Group 2 will be $2.
And so on.
Of course captured NAMED groups will also be returned as follows:
Named group "Test" will be $_rg["Test"]
Named group "Moo" will be $_rg["Moo"]
Named group "Cat" will be $_rg["Cat"]
And so on.
After each regular expression match all capture groups from the previous match will be deleted so its best to copy them if you intend to keep using them.
Regular expressions
Regular expression notation is a compact way of specifying a pattern for strings that can be searched. Regular expressions are character strings in which plain text characters indicate what text should exist in the target string, and a some characters are given special meanings to indicate what variability is allowed in the target string. AutoIt regular expressions are normally case-sensitive.
Regular expressions are constructed of one or more of the following simple regular expression specifiers. If the character is not in the following table, then it will match only itself.
Repeating characters (*, +, ?, {...} ) will try to match the largest set possible, which allows the following characters to match as well, unless followed immediately by a question mark; then it will find the smallest pattern that allows the following characters to match as well.
Nested groups are allowed, but keep in mind that all the groups, except non-capturing groups, assign to the returned array, with the outer groups assigning after the inner groups.
Character escapes
The backslash character (\) in a regular expression indicates that the character that follows it either is a special character (as shown in the following table), or should be interpreted literally. For more information, see Character Escapes in Regular Expressions.
Escaped character Description Pattern Matches \a Matches a bell character, \u0007. \a "\u0007" in "Error!" + '\u0007' \b In a character class, matches a backspace, \u0008. [\b]{3,} "\b\b\b\b" in "\b\b\b\b" \t Matches a tab, \u0009. (\w+)\t "item1\t", "item2\t" in "item1\titem2\t" \r Matches a carriage return, \u000D. (\r is not equivalent to the newline character, \n.) \r\n(\w+) "\r\nThese" in "\r\nThese are\ntwo lines." \v Matches a vertical tab, \u000B. [\v]{2,} "\v\v\v" in "\v\v\v" \f Matches a form feed, \u000C. [\f]{2,} "\f\f\f" in "\f\f\f" \n Matches a new line, \u000A. \r\n(\w+) "\r\nThese" in "\r\nThese are\ntwo lines." \e Matches an escape, \u001B. \e "\x001B" in "\x001B" \ nnn Uses octal representation to specify a character (nnn consists of two or three digits). \w\040\w "a b", "c d" in "a bc d" \x nn Uses hexadecimal representation to specify a character (nn consists of exactly two digits). \w\x20\w "a b", "c d" in "a bc d" \c X \c x Matches the ASCII control character that is specified by X or x, where X or x is the letter of the control character. \cC "\x0003" in "\x0003" (Ctrl-C) \u nnnn Matches a Unicode character by using hexadecimal representation (exactly four digits, as represented by nnnn). \w\u0020\w "a b", "c d" in "a bc d" \ When followed by a character that is "2+2" and "3*9" in "(2+2) * 3*9" not recognized as an escaped character in this and other tables in this topic, matches that character. For example, \* is the same as \x2A, and \. is the same as \x2E. This allows the regular expression engine to disambiguate language elements (such as * or ?) and character literals (represented by \* or \?). \d+[\+-x\*]\d+\d+[\+-x\*\d+
Repeating Characters
Character classes
A character class matches any one of a set of characters. Character classes include the language elements listed in the following table. For more information, see Character Classes in Regular Expressions.
Character class Description Pattern Matches [ character_group ] Matches any single character in character_group. By default, the match is case-sensitive. [ae] "a" in "gray" "a", "e" in "lane" [^ character_group ] Negation: Matches any single character that is not in character_group. By default, characters in character_group are case-sensitive. [^aei] "r", "g", "n" in "reign" [ first - last ] Character range: Matches any single character in the range from first to last. [A-Z] "A", "B" in "AB123" . Wildcard: Matches any single character except \n. To match a literal period character (. or \u002E), you must precede it with the escape character (\.). a.e "ave" in "nave" "ate" in "water" \p{ name } Matches any single character in the Unicode general category or named block specified by name. \p{Lu} "C", "L" in "City Lights" \p{IsCyrillic} "Д", "Ж" in "ДЖem" \P{ name } Matches any single character that is not in the Unicode general category or named block specified by name. \P{Lu} "i", "t", "y" in "City" \P{IsCyrillic} "e", "m" in "ДЖem" \w Matches any word character. \w "I", "D", "A", "1" "3" in "ID A1.3" \W Matches any non-word character. \W " ", "." in "ID A1.3" \s Matches any white-space character. \w\s "D " in "ID A1.3" \S Matches any non-white-space character. \s\S " _" in "int __ctr" \d Matches any decimal digit. \d "4" in "4 = IV" \D Matches any character other than a decimal digit. \D " ", "=", " ", "I" "V" in "4 = IV"
Anchors
Anchors, or atomic zero-width assertions, cause a match to succeed or fail depending on the current position in the string, but they do not cause the engine to advance through the string or consume characters. The metacharacters listed in the following table are anchors. For more information, see Anchors in Regular Expressions.
Assertion Description Pattern Matches ^ The match must start at the beginning of the string or line. ^\d{3} "901" in "901-333-" $ The match must occur at the end of the string or before \n at the end of the line or string. -\d{3}$ "-333" in "-901-333" \A The match must occur at the start of the string. \A\d{3} "901" in "901-333-" \Z The match must occur at the end of the string or before \n at the end of the string. -\d{3}\Z "-333" in "-901-333" \z The match must occur at the end of the string. -\d{3}\z "-333" in "-901-333" \G The match must occur at the point where the previous match ended. \G\(\d\) "(1)", "(3)", "(5)" in "(1)(3)(5)[7](9)" \b The match must occur on a boundary between a \w (alphanumeric) and a \W (nonalphanumeric) character. \b\w+\s\w+\b "them theme", "them them" in "them theme them them" \B The match must not occur on a \b boundary. \Bend\w*\b "ends", "ender" in "end sends endure lender"
Example
Check if a string matches a given pattern :
// Set a string to parse $str = "Hello, World!"; if( $str =~ m/\w+,\s+\w+!/ ) { println("True"); } else { println("False"); }
Check if a string matches a given pattern case insensitive :
// Set a string to parse $str = "Hello, World!"; if( $str =~ m/hello,\s+WORLD!/i ) { println("True"); } else { println("False"); }
Simple matching a string and returning 2 captured groups :
// Set a string to parse $str = 'Account Test Credits 777'; // Do the regex match $str =~ m/Account\s+(\w+)\s+\w+\s+(\d+)/i; println("Account '$1' Credits '$2'"); // Prints // Account 'Test' Credits '777'
Simple matching a string and returning 2 captured groups and saving the variables:
// Set a string to parse $str = 'Account Test Credits 777'; // Do the regex match $str =~ m/Account\s+(\w+)\s+\w+\s+(\d+)/i; $Account = $1; $Credits = $2; println("Account '$Account' Credits '$Credits'"); // Prints // Account 'Test' Credits '777'
Same thing but this time parsing multiple lines of accounts :
// Set a string to parse $str = 'Account Test Credits 777' . @CRLF; $str .= 'Account FoX Credits 1337' . @CRLF; $str .= 'Account Cat Credits 100' . @CRLF; $str .= 'Account Dog Credits 50' . @CRLF; // Do the regex match $str =~ m/Account\s+(\w+)\s+\w+\s+(\d+)/ig; // Print them all for($i = 0; $i < @Groups; $i++) { $Account = $_rg[$i][1]; $Credits = $_rg[$i][2]; println("Match ($i) | Account '" . $Account . "' | Credits '" . $Credits . "'" ); } // Prints // Match (0) | Account 'Test' | Credits '777' // Match (1) | Account 'FoX' | Credits '1337' // Match (2) | Account 'Cat' | Credits '100' // Match (3) | Account 'Dog' | Credits '50'
Case insensitive match on a string to capture all possible matches and return them as a multi-dimensional array :
// Set a string to parse $str = '<test>a</test> <test>b</test> <test>c</Test>'; // Do the regex match $str =~ m/<(?i)test>(.*?)<\/(?i)test>/ig; // How many groups did we find? println("Found groups: " . @Groups); // Print them all for($i = 0; $i < @Groups; $i++) { $match = $_rg[$i]; println("Match ($i) | Text '" . $match[0] . "' | Group text '" . $match[1] . "'" ); } // Prints // Found groups: 3 // Match (0) | Text '<test>a</test>' | Group text 'a' // Match (1) | Text '<test>b</test>' | Group text 'b' // Match (2) | Text '<test>c</Test>' | Group text 'c'
Case insensitive match on a string to capture all possible matches and return them as a single dimension array :
// Set a string to parse $str = '<test>a</test> <test>b</test> <test>c</Test>'; // Do the regex match $str =~ m/<(?i)test>(.*?)<\/(?i)test>/igd; // How many groups did we find? println("Found groups: " . @Groups); // Print them all for($i = 0; $i < @Groups; $i++) { println("Match ($i) | Group text '" . $_rg[$i] . "'" ); } // Prints // Found groups: 3 // Match (0) | Group text 'a' // Match (1) | Group text 'b' // Match (2) | Group text 'c'
Example of using the /x flag
my $a = "xor eax, edx"; $a =~ m/ (\w+) # You can add comments \s* (\w+) \s* # Yup comments all over , \s* (\w+) /x; print( "'$1' -> '$2' -> '$3'" );
Example of using a While loop (While loops with regexp wont work properly without the /g flag)
// Set a string to parse $str = 'Account Test Credits 777' . @CRLF; $str .= 'Account FoX Credits 1337' . @CRLF; $str .= 'Account Cat Credits 100' . @CRLF; $str .= 'Account Dog Credits 50' . @CRLF; while( $str =~ m/Account\s+(\w+)\s+\w+\s+(\d+)/ig ) { $Account = $_rg[$_][1]; $Credits = $_rg[$_][2]; println("Match ($_) | Account '" . $Account . "' | Credits '" . $Credits . "'" ); }
Example of named capture groups
$str = "xor eax, edx"; if( $str =~ m/xor\s*(?<first>\w*),\s*(?<second>\w*)/ ) { println("True: " . $_rg["first"] . " | " . $_rg["second"]); } else { println("False"); }