0

Is it possible to check If no numbers were found in a string when using Regex?

so if I am doing this:

String temp;
String myText = "abcd";
temp = Regex.Match(myText, @"\d+").Value;

How do i check that no numbers were found?

Do i just do this:

if (temp = ""){
//code
}
user2301717
  • 1,049
  • 1
  • 10
  • 13

6 Answers6

3

the better way to do it would be

if (Regex.IsMatch(stringToCheck, @"\d+"){
    // string has number
}

if you want to deal with no numbers found, then try like

if (!Regex.IsMatch(stringToCheck, @"\d+"){
    // no numbers found
}

to find all the matches of number in a string

MatchCollection matches = Regex.Matchs(stringToCheck, @"\d+");

foreach(Match match in matches){
    //Console.WriteLine(match.Value);
}
Parimal Raj
  • 20,189
  • 9
  • 73
  • 110
1

You don't get a match. If you had a match you'd have found a number somewhere.

Geeky Guy
  • 9,229
  • 4
  • 42
  • 62
1

Just do a reverse match with a regex.

if ( !Regex.Match ( stringToCheck, "^[0-9]+$" ).Success ) {

  }
Kevin
  • 532
  • 2
  • 7
1

you can use IsMatch and then negate it

if(!Regex.IsMatch(inp,".*\d.*"))//no number found
Anirudha
  • 32,393
  • 7
  • 68
  • 89
0
Match temp;
String myText = "[0123456789]";
temp = Regex.Match(myText).Value;
bool NoDigits = !temp.Success;

Sorry for the original confusion in my answer. Also, you can keep using the \d flag, I just like [0123456789] because it makes it stand out more in this simplistic case.

BlargleMonster
  • 1,602
  • 2
  • 18
  • 33
  • What do you do when you want to specify `[a-z]`, type them all out? – weston May 17 '13 at 15:21
  • @weston No, but it's easy enough to run my finger across the keyboard and this code snippet is more for explaining the concept that using as few characters as possible (which should **never** be a goal for developers). – BlargleMonster May 17 '13 at 16:21
  • LOL (to running finger over keyboard comment)! No I'm not concerned about the code's length in this case, just code quality. I think it's bad practice to avoid the tools that are given to you just in order to dumb it down for someone. Give people some credit. Also the range (`[0-9]`) and digit (`\d`) implementations may well be more efficient, just think how each would be implemented compared to a character set implementation like yours. – weston May 17 '13 at 17:37
  • Efficiency isn't something I considered. I just assumed the implementation would convert the shorthand into the same value before actually running the regex, but that's actually something to consider now that you mention it. – BlargleMonster May 17 '13 at 17:44
  • BTW, this sparked some investigation on my part, with some surprising results: http://stackoverflow.com/questions/16621738/d-less-efficient-than-0-9 – weston May 18 '13 at 12:07
0
String myText = "abcd";

if (Regex.IsMatch(myText, "[0-9]+"))
{
    // there was a number
} else {
    // no numbers
}
Jason P
  • 26,984
  • 3
  • 31
  • 45