简体   繁体   中英

How to extract first character and numbers after that until find a character (a-z) in a string - C# 2.0

How to extract numbers from a second index of a string until find a character (az) in a string?

I am using C# version 2.0 (can't upgrade for some reasons).

Here are some examples;

  • M000067TGFD45F = M000067
  • B000064TFR765TXT = B000064
  • B000065TFR765 = B000065
  • B000067TGFD = B000067

I have tried Regex("[^0-9]") which works if there is no character after digits (4th example)

 "B" + regexOnlyNumbers.Replace(mystring, string.Empty);

You can use

string text = "M000067TGFD45F";
Match m = Regex.Match(text, @"^[A-Z][0-9]+");
if (m.Success)
{
    Console.WriteLine(m.Value);
}

See the regex demo .

Details

  • ^ - start of string
  • [AZ] - an uppercase ASCII letter
  • [0-9]+ - one or more ASCII digits.

Alternatively, you might consider a ^[AZ][^AZ]+ pattern, where [^AZ]+ matches any one or more chars other than uppercase ASCII letters.

To ignore case, use RegexOptions.IgnoreCase : Regex.Match(text, @"^[AZ][0-9]+", RegexOptions.IgnoreCase) .

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