vmb
vmb

Reputation: 3028

How to check String Contains Alphabets or Digits-Regular Expression c#

How to check Whether string contains Alphabets or Digits using Regular Expression. In a single regular expression How can i achieve this in c#.Currently i am finding alphabets like this

 Regex.Matches(folderPath, @"[a-zA-Z]").Count

Upvotes: 1

Views: 3202

Answers (3)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626845

In C#, you do not need regex to check if there are digits or alphabetic characters. Use LINQ with Char.IsLetterOrDigit():

var hasAlphanum = "!?A1".Any(p => Char.IsLetterOrDigit(p)); // => true
var hasAlphanum1 = "!?1".Any(p => Char.IsLetterOrDigit(p)); // => true
var hasAlphanum2 = "!?".Any(p => Char.IsLetterOrDigit(p));  // => false

The .Any(p => Char.IsLetterOrDigit(p)) part is checking if any character inside the string conforms to the condition inside the brackets.

Upvotes: 1

BhavO
BhavO

Reputation: 2399

Do this:

string folderPath = "abc123";
Regex.IsMatch(folderPath, @"[a-zA-Z0-9]") // returns true

https://dotnetfiddle.net/faeZND

Upvotes: 0

anubhava
anubhava

Reputation: 785156

Whether string contains Alphabets or Digits

For this case:

Regex.Matches(folderPath, @"[a-zA-Z0-9]").Count

should work.

Upvotes: 3

Related Questions