简体   繁体   中英

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:

// 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. Or you could check that match.Index was 0 if you wanted...

To check if my string begins with number, you need to use pattern ^\\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:

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 :

var length = 0;

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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