Perry_M
Perry_M

Reputation: 137

Autohotkey extract text using regex

I am just now learning regex using autohotkey but can't figure out how to extract specific string and save to a variable?

Line of text I am searching: T NW CO NORWALK HUB NW 201-DS3-WLFRCTAICM5-NRWLCT02K16 [DS3 LEC] -1 -1 PSTN

I am trying to save, NW 201-DS3-WLFRCTAICM5-NRWLCT02K16 [DS3 LEC] ONLY.

Here is my regex code: NW\D\d.DS3.]

But how do I store that as a variable in autohotkey?

I have tried RegexMatch but that only shows the position. I am doing something wrong.

Upvotes: 4

Views: 2848

Answers (2)

JamesHeo
JamesHeo

Reputation: 61

; If you want to delete ALL ....

Only(ByRef C)
{

/*
RegExReplace
https://autohotkey.com/docs/commands/RegExReplace.htm
*/

; NW 201-DS3-WLFRCTAICM5-NRWLCT02K16 [DS3 LEC] 

C:=RegExReplace(C, "NW\s[\w-]+\s\[[\w\s]+\]","",ReplacementCount,-1) 

if (ReplacementCount = 0)
return C
else
return Only(C)

} ; Only(ByRef C)

string:="Line of text I am searching: T NW CO NORWALK HUB NW 201-DS3-WLFRCTAICM5-NRWLCT02K16 [DS3 LEC] -1 -1 PSTN"

Result:=Only(string)
MsgBox, % Result
MsgBox, % Only(string)

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626748

You may provide the third argument that will hold the match array:

RegExMatch(str,"NW\D\d.*DS3.*\]",matches)

Then, matches[0] will contain the match.

If you use capturing groups inside the pattern, you will be able to access their values by using further indices. If you use "NW\D(\d.*DS3.*)\]" against "NW 5xxx DS3 yyy], you will have the whole string inside matches[0] and matches[1] will hold 5xxx DS3 yyy.

See AHK RegExMatch docs:

FoundPos := RegExMatch(Haystack, NeedleRegEx [, UnquotedOutputVar = "", StartingPosition = 1])

UnquotedOutputVar Mode 1 (default): OutputVar is the unquoted name of a variable in which to store the part of Haystack that matched the entire pattern. If the pattern is not found (that is, if the function returns 0), this variable and all array elements below are made blank.

If any capturing subpatterns are present inside NeedleRegEx, their matches are stored in a pseudo-array whose base name is OutputVar. For example, if the variable's name is Match, the substring that matches the first subpattern would be stored in Match1, the second would be stored in Match2, and so on. The exception to this is named subpatterns: they are stored by name instead of number. For example, the substring that matches the named subpattern "(?P<Year>\d{4})" would be stored in MatchYear. If a particular subpattern does not match anything (or if the function returns zero), the corresponding variable is made blank.

Upvotes: 2

Related Questions