0

I'm trying to put a condition to allow only letters to be used

my condition is

  if (Regex.IsMatch(txtfirstname.Text, "[A-Za-z]"))
  {
      usersEl.firstName = txtfirstname.Text;
  }

if the txt was only numbers or other symbols, it doesn't go inside the block, and if it was letters it go inside it. but the problem is if it was letters and numbers, it also go inside the block which it shouldn't since there are numbers!

could any one please give me which regular expression should I use if I want it to be ONLY letters or ONLY numbers without any symbols.

Leanah_as
  • 99
  • 2
  • 2
  • 11

6 Answers6

1

You can use ^[A-Za-z]+$ for only letters and ^\d+$ for only numbers.

Titus
  • 22,031
  • 1
  • 23
  • 33
1

Here's a link to a similar question: Regular Expression to match only alphabetic characters

TLDR; ^[A-Za-z]+$

The caret ^ denotes that it will match only the beginning of the string. The + is for repetition: match the pattern (alphabetical) 1 or more times The $ denotes that it will match the end of the line This will mean that there can be no spaces.

"aasdfasdfasdfasdfasdf" --Match
"asdfasdf asfasdf asdf" --No Match
"asdfasfasdf      "     --No Match
(blank line)            --No Match
"A"                     --Match (if no spaces after the A)

Replace [A-Za-z] with [0-9] to match only numbers

Community
  • 1
  • 1
0

You can do this by using the following code

var filter = @"/^[A-z]+$/";
Regex reg = new Regex(filter);
if (reg.IsMatch(txtfirstname.Text))
{
    usersEl.firstName = txtfirstname.Text;
}

hope this helps

anand
  • 1,559
  • 5
  • 21
  • 45
0

For only numbers you could use

([0-9])+

For non-digit characters you could simply use

(\D)+
Kemal
  • 96
  • 8
0

If you want to visualize RegEx in a more human readable form, then use this site:

http://regexper.com/#%2F%5E%5BA-z%5D%2B%24%2F

I've already included the answer from anand.

Tomas Nilsson
  • 228
  • 2
  • 4
0

You can use LINQ as regex involves a lot of overhead:

if (!String.IsNullOrEmpty(txtfirstname.Text) && txtfirstname.Text.All(c => Char.IsLetter(c)))
{
}

For other scenarios, use Char.IsDigit, Char.IsLetterOrDigit etc.

w.b
  • 11,026
  • 5
  • 30
  • 49