Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# - check if string contains character and number

How do I check if a string contains the following characters "-A" followed by a number?

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

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

like image 316
user1481183 Avatar asked Dec 01 '22 23:12

user1481183


2 Answers

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

If you actually want to extract the -A[num] bit then 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 - such as if you need to extract the A[num] bit on its own or just the number:

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

Or as in my first suggestion, if you want the '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 the non-capturing group (?<=) because, as the name implies, it keeps the output groups clean.

like image 20
Andras Zoltan Avatar answered Dec 26 '22 06:12

Andras Zoltan


It can be done with a regular expression:

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

The \d matches any digit.

See it working online: ideone

like image 114
Mark Byers Avatar answered Dec 26 '22 06:12

Mark Byers