wetin
wetin

Reputation: 438

Extract a substring using AHK regex matching

I was unable to find a solution for this question. Difficult to ask properly without giving an example.

I have file names. Here's an example format: Diagnostics 20200826-12345moretext.zip

As you can see, the date is built into the filename at some point in the filename. I want to match "2020XXZZ" but I want to store XX to a variable. Is that possible with RegExMatch?

something like regexmatch(file_name, "202[0-9]{3}", out_var)

If not possible I suppose I can extract that last characters off the out_var but I was hoping for the right way to do this (if exists, which I think there is a way).

Upvotes: 0

Views: 1847

Answers (1)

0x464e
0x464e

Reputation: 6489

Yes, this is very doable.
It's going to be easy to do with capture groups (AHK documentation | General Regex tutorial).

So we can use a Regex as simple as this 2020(\d{2}).
You could add in more checks to the Regex if you expect the file names to be something which could result in matching the wrong thing.

When we use this Regex in AHK, we're going to want to start off the pattern with O) (see OutputVar Mode 3) to indicate we're outputting a match object.
Then we can access the first captured group with e.g out_var.Value(1) or out_var[1].

file := "Diagnostics 20200826-12345moretext.zip"

if(RegExMatch(file, "O)2020(\d{2})", out_var))
   MsgBox, % "First two numbers after ""2020"": " out_var[1]
else
   MsgBox, % "Failed to match!"

Alternatively, to not use capture groups, you could use lookarounds to match only the two numbers you want. In this case you wouldn't output a match object either.
Personally I'd say capture groups would be the better/more common approach and they're definitely good to learn, but if you're interested, here it is with a lookaround as well: (?<=2020)\d{2}.

file := "Diagnostics 20200826-12345moretext.zip"

if(RegExMatch(file, "(?<=2020)\d{2}", out_var))
   MsgBox, % "First two numbers after ""2020"": " out_var
else
   MsgBox, % "Failed to match!"

Upvotes: 3

Related Questions