繁体   English   中英

特定子串的长度

[英]Length of specific substring

我检查我的字符串是否以数字开头

if(RegEx(IsMatch(myString, @"\d+"))) ...

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

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

好吧,而不是使用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如果您想要,则match.Index为0 ...

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

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

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

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

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

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

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

不要只是检查IsMatch ,而是获得匹配,以便获得有关它的信息,例如长度:

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

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

如果再多出一些代码,可以利用Regex.Match

var length = 0;

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

if(match.Success)
{
    length = match.Value.Length;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM