Home > Net >  How to match regex only for certain string literals?
How to match regex only for certain string literals?

Time:10-27

I want to create regex that matches a digit, followed by the string A, B or AB.

Should match:

0A
0B
0AB

not:

0AA
0BB
0BA

I started as follows, but that would also match the values below that I don't want to match:

[0-9][AB] 

Of course this is due to the [AB] group. But how can I only match like A|B|AB?

CodePudding user response:

You may use this regex:

^\d(?:[AB]|AB)?$

RegEx Demo

It matches a digit at the start followed by A or B using character class [AB] or just AB as an alternative.

CodePudding user response:

Using [AB] matches 1 or more times either A or B, and the pattern is unanchored to is can partially match in 0ABC

You can match either A followed by an optional B, or a single B.

^\d(?:AB?|B)$

Regex demo

Or with word boundaries:

\b\d(?:AB?|B)\b

CodePudding user response:

Or this way:

\dA?B?

A digit with 0 or 1 "A" and 0 or 1 "B".

  • Related