Basically, I want to count sets of specific characters in a string. In other words I need to count all Letters and Numbers, and nothing else. But I cant seem to find the right (regex) syntax. Here's what i have ...
基本上,我想计算一个字符串中的特定字符集。换句话说,我需要统计所有的字母和数字,而不是其他任何东西。但我似乎无法找到正确的(正则表达式)语法。这是我的...
public double AlphaNumericCount(string s)
{
double count = Regex.Matches(s, "[A-Z].[a-z].[0-9]").Count;
return count;
}
I've been looking around, but cant seem to find anything that allows more than one set of characters. Again, I'm not sure on the syntax maybe it should be "[A-Z]/[a-z]/[0-9]" or something. Anywho, go easy on me - its my first day using Regex.
我一直在环顾四周,但似乎找不到任何允许多个角色的东西。同样,我不确定语法可能应该是“[A-Z] / [a-z] / [0-9]”或其他什么。 Anywho,对我来说很容易 - 这是我使用正则表达式的第一天。
Thanks.
谢谢。
4 个解决方案
#1
5
Regular Expression Cheat Sheet
正则表达式备忘单
Expresso Regular Expression tool
Expresso正则表达式工具
[A-Z].[a-z].[0-9]
will match any capital letter ([A-Z]
), followed by any character (.
), followed by any lower case letter ([a-z]
), followed by any character (.
), followed by any number ([0-9]
).
[AZ]。[az]。[0-9]将匹配任何大写字母([AZ]),后跟任何字符(。),后跟任何小写字母([az]),后跟任何字符(。 ),后跟任意数字([0-9])。
What you want to match on any letter or number is [A-Za-z0-9]
.
您希望在任何字母或数字上匹配的是[A-Za-z0-9]。
#2
4
If the use of regular expressions is not required, there is an easy, alternate solution:
如果不需要使用正则表达式,那么有一个简单的替代解决方案:
return s.ToCharArray().Count(c => Char.IsNumber(c) || Char.IsLetter(c));
#4
3
If you want to avoid regular expressions, you can simply iterate through the characters in the string and check if they're a letter or digit using Char.IsLetterOrDigit.
如果要避免使用正则表达式,可以简单地遍历字符串中的字符,并使用Char.IsLetterOrDigit检查它们是字母还是数字。
public int AlphaNumericCount(string s)
{
int count = 0;
for(int i = 0; i < s.Length; i++)
{
if(Char.IsLetterOrDigit(s[i]))
count++;
}
return count;
}
#1
5
Regular Expression Cheat Sheet
正则表达式备忘单
Expresso Regular Expression tool
Expresso正则表达式工具
[A-Z].[a-z].[0-9]
will match any capital letter ([A-Z]
), followed by any character (.
), followed by any lower case letter ([a-z]
), followed by any character (.
), followed by any number ([0-9]
).
[AZ]。[az]。[0-9]将匹配任何大写字母([AZ]),后跟任何字符(。),后跟任何小写字母([az]),后跟任何字符(。 ),后跟任意数字([0-9])。
What you want to match on any letter or number is [A-Za-z0-9]
.
您希望在任何字母或数字上匹配的是[A-Za-z0-9]。
#2
4
If the use of regular expressions is not required, there is an easy, alternate solution:
如果不需要使用正则表达式,那么有一个简单的替代解决方案:
return s.ToCharArray().Count(c => Char.IsNumber(c) || Char.IsLetter(c));
#3
#4
3
If you want to avoid regular expressions, you can simply iterate through the characters in the string and check if they're a letter or digit using Char.IsLetterOrDigit.
如果要避免使用正则表达式,可以简单地遍历字符串中的字符,并使用Char.IsLetterOrDigit检查它们是字母还是数字。
public int AlphaNumericCount(string s)
{
int count = 0;
for(int i = 0; i < s.Length; i++)
{
if(Char.IsLetterOrDigit(s[i]))
count++;
}
return count;
}