user8836597
user8836597

Reputation: 13

How to match different substring using perl regular expression?

Take below strings for example

abc12, abc13, abc23, abc288, abd12

What regular string should be used if I only want to match abc12 and abc13.

I thought it should be abc[(12)|(13)], so 12 and 13 will be grouped together and match either of them, but it turns out, this string will match all strings above.

Upvotes: 1

Views: 124

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521914

Your current regex is not doing what you think it is:

abc[(12)|(13)]

This says to match abc followed by any one of the following characters:

1, 2, 3, (, ), or |

The characters inside the bracket are part of a character class, or group of characters which can be matched. For your use case, you probably want something like this:

abc1[23]

This matches abc1 followed by only a 2 or a 3.

If you wanted to match abc12 or abc23 you could use this:

abc(?:12|23)

Here we can't really use a character class, but we can use an alternation instead. The quantity in parentheses will match either 12 or 23. If you are wondering what ?: does, it simply tells the Perl regex engine not to capture what is inside parentheses, which is what it would be doing by default.

Upvotes: 3

Related Questions