c# - check if string contains character and number

11,421

Solution 1

It can be done with a regular expression:

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

The \d matches any digit.

See it working online: ideone

Solution 2

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.

Share:
11,421
user1481183
Author by

user1481183

Updated on June 16, 2022

Comments

  • user1481183
    user1481183 almost 2 years

    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

    • gdoron is supporting Monica
      gdoron is supporting Monica almost 12 years
      What have you tried? since you already know it's called regex, finding an answer should take less than a minute.
    • Ωmega
      Ωmega almost 12 years
      How about thisIsaString-A21B something else is it ok?
  • Andras Zoltan
    Andras Zoltan almost 12 years
    ...except \d will only match a single digit whereas the example given is -A21, so presumably the OP requires both digits
  • Mark Byers
    Mark Byers almost 12 years
    @AndrasZoltan: That's a relevant concern if you want to extract the number (as in your answer) but it's not relevant if you just want to test if there is a match.
  • Mark Byers
    Mark Byers almost 12 years
    +1 For also showing how to extract the number, though I guess the OP only wanted "yes" or "no" in this case. ;-)
  • Ponmalar
    Ponmalar almost 11 years
    If s = "C:\\", and Regex.IsMatch(s, @"-A\d") is false