Regular expression with numbers and special characters, but no letters

I am creating a regular expression that accepts input with any decimal number (0-9), +, * or #, but should not accept any letters (az).

so numbers like

  • # 192 #
  • * 31 # + 32475728966
  • 0479266315
  • +32495959511

.

The regular expression is not valid if there is a letter in the string.

  • # 192 # abbef
  • a0479266315

This is the regex that I still have:

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 at # 192 # abbef

How can i fix this?

+6
source share
4 answers

You can use this:

 private const string PhoneNumberRegex = @"^[0-9*#+]+$"; 

Where ^ and $ are anchors for the beginning and end of the line.

Note: RegexOptions.IgnoreCase not required.

+8
source

You need to bind the string to ^ (beginning of line) and $ (end of line). Otherwise, your string will match if any part of it matches.

In addition, you need at least one of these characters (you do not want to match an empty string, so you must use + (one or more).

Finally, you can make a character class from all of your characters: [\d*#+] .

Combining all this, you will receive:

 private const string PhoneNumberRegex = "^[\\d*#+]+$"; 

This means that from the beginning of the line to the end, you need one or more of the characters you list.

+3
source

I believe that this will satisfy your needs.

 private const string PhoneNumberRegex = @"^([0-9]|#|\+|\*)+$" 
0
source

All Articles