Reputation: 4661
I'm making a regex that accepts an input with any decimal(0-9), +, * or # but shouldn't accept any letters(a-z).
so numbers like
should be accepted.
The regex is invalid when there is any letter in the string.
This is the regex I have so far:
private const string PhoneNumberRegex = "((\\d)|(\\*)|(\\#)|(\\+))?";
private bool IsValid(inputString)
{
// Accept * # + and number
Match match = Regex.Match(inputString, PhoneNumberRegex, RegexOptions.IgnoreCase);
return match.Success;
}
But this regex also returns true on #192#abbef
How can I fix this?
Upvotes: 13
Views: 65331
Reputation: 4078
You need to anchor your string with ^
(begin of line) and $
(end of line). Otherwise your string matches if any part of it matches.
Also, you want at least one of those characters (you don't want to match an empty string, so you should use +
(one or more).
Lastly, you can make a character class out of all your characters: [\d*#+]
.
Putting it all together gives you:
private const string PhoneNumberRegex = "^[\\d*#+]+$";
This means that from the beginning of the string till the end, you want one or more of those characters you listed.
Upvotes: 5
Reputation: 8839
Use this :
const string MYRegex = @"^[0-9*#+]+$";
for more information plz visit
http://www.regexlib.com/Search.aspx?k=special%20characters&AspxAutoDetectCookieSupport=1
http://www.cisco.com/en/US/docs/ios_xr_sw/iosxr_r3.4/getting_started/installation/guide/gs34aexp.pdf
Upvotes: 0
Reputation: 904
I believe this will meet your needs
private const string PhoneNumberRegex = @"^([0-9]|#|\+|\*)+$"
Upvotes: 2
Reputation: 89557
You can use this:
private const string PhoneNumberRegex = @"^[0-9*#+]+$";
Where ^
and $
are anchors for start and end of the string.
Note: RegexOptions.IgnoreCase
is not needed.
Upvotes: 19