简体   繁体   中英

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

It can be done with a regular expression:

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

The \\d matches any digit.

See it working online: ideone

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM