Home > OS >  Regex: Check If String Contains A Single Instance of the Letter "A" or "B"
Regex: Check If String Contains A Single Instance of the Letter "A" or "B"

Time:10-11

I am completely new to the world of Regular Expressions, and was wondering if someone could provide me with some assistance on getting an expression going.

In my scenario, I need to check if a string contains one letter, and the one letter can either be an A or B. Only phrases with a single letter as A or B are permitted.

enter image description here

Ideally the expression would identify the "Good" values as matches and reject the "Bad" values due to containing multiple letters and not a single A or B.

Any help would be very much appreciated

Thanks!

CodePudding user response:

If you just need the result and regex is not mandatory, you could use a simple expression as below

bool result = word.Where(Char.IsLetter).Count() == 1 && (word.Contains('A') || word.Contains('B'));

CodePudding user response:

The expression ^[^A-Z]*[AB][^A-Z]*$ matches a string containing exactly one letter that is either A or B.

Explanation:

^        Matches the start of the string.
[^A-Z]   Matches any character that is not a lette
*        Means zero or more of the previous item, thus
         [^A-Z]* Matches zero or more characters that are not letters
[AB]     Matches either an `A` or a `B`
[^A-Z]*  Matches zero or more characters that are not letters
$        Matches the end of the string

If the string should contain at least one character before and after the A or B then the pattern should be modified to be ^[^A-Z] [AB][^A-Z] $. Using the means matching be one or more of the previous item whereas the * means zero or more.

The pattern [A-Z] matches any letter. [^A-Z] matches any character that is not a letter. Similarly [AB] matches either an A or a B. [^AB] matches any character that is not A or B, but this pattern is not needed here. Putting these together gives t

CodePudding user response:

Try this pattern:

"[^AB]*[AB][^AB]*"
  • Related