tags:

views:

841

answers:

6

Ok sorry this might seem like a dumb question but I cannot figure this thing out :

I am trying to parse a string and simply want to check whether it only contains the following characters : '0123456789dD+ '

I have tried many things but just can't get to figure out the right regex to use!


  Regex oReg = new Regex(@"[\d dD+]+");
  oReg.IsMatch("e4");

will return true even though e is not allowed... I've tried many strings, including Regex("[1234567890 dD+]+")...

It always works on Regex Pal but not in C#...

Please advise and again i apologize this seems like a very silly question

+8  A: 

try this:

@"^[0-9dD+ ]+$"

The ^ and $ at the beginning and end signify the beginning and end of the input string respectively. Thus between the beginning and then end only the stated characters are allowed. In your example, the regex matches if the string contains one of the characters even if it contains other characters as well.

@comments: thanks. I fixed the missing + and space.

Manu
I think that your example needs another + or * before the $, it currently only matches a single character
Carl
looks like he fixed it.
Joel Coehoorn
^[\ddD+]$ is also good.
leppie
Missed the space...
Marc Gravell
+2  A: 

Oops, you forgot the boundaries, try:

Regex oReg = new Regex(@"^[0-9dD +]+$");
oReg.IsMatch("e4");

^ matches the begining of the text stream, $ matches the end.

Coincoin
Space was allows by the original pattern
Marc Gravell
A: 

I believe it's returning True because it's finding the 4. Nothing in the regex excludes the letter e from the results.

Ian Jacobs
+1  A: 

It is matching the 4; you need ^ and $ to terminate the regex if you want a full match for the entire string - i.e.

    Regex re = new Regex(@"^[\d dD+]+$");
    Console.WriteLine(re.IsMatch("e4"));
    Console.WriteLine(re.IsMatch("4"));
Marc Gravell
A: 

Another option is to invert everything, so it matches on characters you don't want to allow:

Regex oReg = new Regex(@"[^0-9dD+]");
!oReg.IsMatch("e4");
Joel Coehoorn
+1  A: 

This is because regular expressions can also match parts of the input, in this case it just matches the "4" of "e4". If you want to match a whole line, you have to surround the regex with "^" (matches line start) and "$" (matches line end).

So to make your example work, you have to write is as follows:

Regex oReg = new Regex(@"^[\d dD+]+$");
oReg.IsMatch("e4");