Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex with numbers and special characters but no letters

Tags:

c#

regex

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

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

should be accepted.

The regex is invalid when there is any letter in the string.

  • #192#abbef
  • a0479266315

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?

like image 960
Robby Smet Avatar asked Dec 20 '13 14:12

Robby Smet


Video Answer


1 Answers

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.

like image 130
Casimir et Hippolyte Avatar answered Oct 21 '22 15:10

Casimir et Hippolyte