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
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.
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With