Reputation: 3028
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
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
Reputation: 2399
Do this:
string folderPath = "abc123";
Regex.IsMatch(folderPath, @"[a-zA-Z0-9]") // returns true
https://dotnetfiddle.net/faeZND
Upvotes: 0
Reputation: 785156
Whether string contains Alphabets or Digits
For this case:
Regex.Matches(folderPath, @"[a-zA-Z0-9]").Count
should work.
Upvotes: 3