Richard Millen
Richard Millen

Reputation: 63

Regular Expression to match multiple groups

I'm trying to write a regular expression to match strings containing two different groups of hexadecimal numbers 4 characters in length, separated by a hyphen. e.g.

00AA-10F2
14ED-7F09
1A20-A55F

This expression works ok,

[0-9A-F]{4}-[0-9A-F]{4}

but I was wondering if there's a more concise way of achieving the same thing.

I'm using C++11 std::regex (currently in default / ECMAScript mode) in case that makes a difference.

Any advice would be really appreciated!

Thanks,

Rich.

Upvotes: 0

Views: 353

Answers (1)

jotik
jotik

Reputation: 17900

Not really. You could write expressions like

([0-9A-F]{4}-?){2}

or

(-?[0-9A-F]{4}){2}

But the former would also match strings like 00AA-10F2-, 00AA10F2- and the latter would also match -00AA-10F2 and -00AA10F2. There is no shorter way to write the regular expression [0-9A-F]{4}-[0-9A-F]{4}.

You could however use plain C++ tricks like:

std::string subexpression("[0-9A-F]{4}");
std::regex regularExpression(subexpression + "-" + subexpression);

Alternatively, modes other than the default ECMAScript mode may provide regular expressions syntax which allows certain subexpressions to be repeated, but support other modes in C++ implementations may be lacking.

Upvotes: 1

Related Questions