特定子串的长度

时间:2012-06-02 18:57:30

标签: java c# regex maxlength digit

我使用

检查我的字符串是否以数字开头
if(RegEx(IsMatch(myString, @"\d+"))) ...

如果这个条件成立,我想得到我的字符串开头的这个“数字”子字符串的长度。

我可以找到长度检查,如果每个下一个字符都是从第一个字符开始的数字并增加一些计数器。有没有更好的方法呢?

6 个答案:

答案 0 :(得分:6)

好而不是使用IsMatch,你应该找到匹配:

// Presumably you'll be using the same regular expression every time, so
// we might as well just create it once...
private static readonly Regex Digits = new Regex(@"\d+");

...

Match match = Digits.Match(text);
if (match.Success)
{
    string value = match.Value;
    // Take the length or whatever
}

请注意,此不会检查数字是否出现在字符串的开头。您可以使用@"^\d+"来完成此操作,这会将匹配锚定到开头。或者,如果您愿意,可以检查match.Index是否为0

答案 1 :(得分:4)

要检查我的字符串是否以数字开头,您需要使用模式^\d+

string pattern = @"^\d+";
MatchCollection mc = Regex.Matches(myString, pattern);
if(mc.Count > 0)
{
  Console.WriteLine(mc[0].Value.Length);
}

答案 2 :(得分:3)

您的正则表达式检查您的字符串是否包含一个或多个数字的序列。如果你想检查它是否以它开头,你需要在开头锚定它:

Match m = Regex.Match(myString, @"^\d+");
if (m.Success)
{
    int length = m.Length;
}

答案 3 :(得分:1)

作为正则表达式的替代方法,您可以使用扩展方法:

int cnt = myString.TakeWhile(Char.IsDigit).Count();

如果字符串开头没有数字,您自然会得到零计数。否则你有数字位数。

答案 4 :(得分:0)

不要只检查IsMatch,而是获取匹配信息,以便获取相关信息,例如长度:

var match = Regex.Match(myString, @"^\d+");
if (match.Success)
{
    int count = match.Length;
}

另外,我在模式的开头添加了^,将其限制在字符串的开头。

答案 5 :(得分:0)

如果您更多地分解代码,可以利用Regex.Match

var length = 0;

var myString = "123432nonNumeric";
var match = Regex.Match(myString, @"\d+");

if(match.Success)
{
    length = match.Value.Length;
}
相关问题