1

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.

1
  • 1
    I am not sure what you want to do, but $str =~ /^abc1(?:2|3)$/ will match only abc12 and abc13 Commented Oct 26, 2017 at 9:24

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

abc1[23] work for this example. But what if I want to match abc12 and abc23, whatever I just mean to match several substrings inside a regular expresssion. Is it possible? Thanks a lot.
Excellent! That's exactly what I want, I know the expression ?:, but never thought it could do this! Thanks a lot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.