AUTOHOTKEY: RegExMatch() a series of numbers and letters

2.3k views Asked by At

I've tested my regular expression in http://www.regextester.com/

([0-9]{4,4})([A-Z]{2})([0-9]{1,3})

It's matching perfect with the following strings just as I want it.

1234AB123
2000AZ20
1000XY753

But when I try it in Autohotkey I get 0 result

test := RegExMatch("2000SY155","([0-9]{4,4})([A-Z]{2})([0-9]{1,3})")

MsgBox %test%

testing for:

  • first 4 characters must be a number
  • next 2 characters must be caps letters
  • next 1 to 3 characters must be numbers
2

There are 2 answers

2
errorseven On BEST ANSWER

You had to many ( )

This is the correct implementation:

test := RegExMatch("1234AB123","[0-9]{4,4}([A-Z]{2})[0-9]{1,3}")

Edit:

So what I noticed is you want this pattern to match, but you aren't really telling it much.

Here's what I was able to come up with that matches what you asked for, it's probably not the best solution but it works:

test := RegExMatch("1234AB567","^[0-9]{4,4}[A-Z]{2}(?![0-9]{4,})[0-9$]{1,3}")

Breaking it down:

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

Circumflex (^) and dollar sign ($) are called anchors because they don't consume any characters; instead, they tie the pattern to the beginning or end of the string being searched.

^ may appear at the beginning of a pattern to require the match to occur at the very beginning of a line. For example, ** ** matches abc123 but not 123abc.

$ may appear at the end of a pattern to require the match to occur at the very > end of a line. For example, abc$ matches 123abc but not abc123.

So by adding Circumflex we are requiring that our Pattern [0-9]{4,4} be at the beginning of the our Haystack.

Look-ahead and look-behind assertions: The groups (?=...), (?!...) are called assertions because they demand a condition to be met but don't consume any characters.

(?!...) is a negative look-ahead because it requires that the specified pattern not exist.

Our next Pattern is looking for two Uppercase Alpha Characters [A-Z]{2}(?![0-9]{4,}) that does not have four or more Numeric characters after it.

And finally our last Pattern that needs to match one to three Numeric characters as the last characters in our Haystack [0-9$]{1,3}

0
phil294 On
test := RegExMatch("2000SY155","([0-9]{4,4})([A-Z]{2})([0-9]{1,3})")
MsgBox %test%

But when I try it in Autohotkey I get 0 result

The message box correctly returns 1 for me, meaning your initial script works fine with my version. Usually, braces are no problem in RegExes, you can put there as many as you like... maybe your AutoHotkey version is outdated?