Reputation: 42316
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
Upvotes: 2
Views: 1430
Reputation: 29153
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.
Upvotes: 8
Reputation: 28606
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.
Upvotes: 2
Reputation:
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");
Upvotes: 1
Reputation: 416049
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");
Upvotes: -1
Reputation: 1063413
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"));
Upvotes: 1
Reputation: 5501
I believe it's returning True because it's finding the 4. Nothing in the regex excludes the letter e from the results.
Upvotes: 0