简体   繁体   English

特定子串的长度

[英]Length of specific substring

I check if my string begins with number using 我检查我的字符串是否以数字开头

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

If this condition holds I want to get the length of this "numeric" substring that my string begins with. 如果这个条件成立,我想得到我的字符串开头的这个“数字”子字符串的长度。

I can find the length checking if every next character is a digit beginning from the first one and increasing some counter. 我可以找到长度检查,如果每个下一个字符都是从第一个字符开始的数字并增加一些计数器。 Is there any better way to do this? 有没有更好的方法来做到这一点?

Well instead of using IsMatch , you should find the match: 好吧,而不是使用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
}

Note that this doesn't check that the digits occur at the start of the string. 请注意,这不会检查数字是否出现在字符串的开头。 You could do that using @"^\\d+" which will anchor the match to the beginning. 您可以使用@"^\\d+"来执行此操作,这会将匹配锚定到开头。 Or you could check that match.Index was 0 if you wanted... 或者您可以检查match.Index如果您想要,则match.Index为0 ...

To check if my string begins with number, you need to use pattern ^\\d+ . 要检查我的字符串是否以数字开头 ,您需要使用模式^\\d+

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

Your regex checks if your string contains a sequence of one or more numbers. 您的正则表达式检查您的字符串是否包含一个或多个数字的序列。 If you want to check that it starts with it you need to anchor it at the beginning: 如果你想检查它是否以它开头,你需要在开头锚定它:

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

As an alternative to a regular expression, you can use extension methods: 作为正则表达式的替代方法,您可以使用扩展方法:

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

If there are no digits in the beginning of the string you will naturally get a zero count. 如果字符串开头没有数字,您自然会得到零计数。 Otherwise you have the number of digits. 否则你有数字位数。

Instead of just checking IsMatch , get the match so you can get info about it, like the length: 不要只是检查IsMatch ,而是获得匹配,以便获得有关它的信息,例如长度:

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

Also, I added a ^ to the beginning of your pattern to limit it to the beginning of the string. 另外,我在模式的开头添加了^ ,将其限制为字符串的开头。

If you break out your code a bit more, you can take advantage of Regex.Match : 如果再多出一些代码,可以利用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