C # - check if string contains character and number

How to check if a string contains the following characters "-A" and then a number?

Ex: thisIsaString-A21 = yes, contains "-A" followed by a number

Ex: thisIsaNotherString-AB21 = no, does not contain "-A" followed by a number

+4
source share
2 answers

This can be done using a regex:

if (Regex.IsMatch(s, @"-A\d")) { ... } 

\d matches any digit.

See how it works on the Internet: ideone

+15
source
 if(Regex.IsMatch("thisIsaString-A21", "-A\\d+")) { //code to execute } 

If you really want to extract the -A [num] bit, you can do this:

 var m = Regex.Match("thisIsaString-A21", "-A\\d+")); if(m.Success) { Console.WriteLine(m.Groups[0].Value); //prints '-A21' } 

There are other things you can do — for example, if you need to extract the A [num] bit yourself or just a number:

 var m = Regex.Match("thisIsaString-A21", "(?<=-A)\\d+"); //now m.Groups[0].Value contains just '21' 

Or, as in my first sentence, if you want "A21":

 var m = Regex.Match("thisIsaString-A21", "(?<=-)A\\d+"); //now m.Groups[0].Value contains 'A21' 

There are other ways to achieve these last two — I like a non-capture group (?<=) , Because, as the name suggests, it retains pure output groups.

+4
source

All Articles