简体   繁体   English

如何提取第一个字符和之后的数字,直到在字符串中找到字符 (az) - C# 2.0

[英]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?如何从字符串的第二个索引中提取数字直到在字符串中找到字符(az)?

I am using C# version 2.0 (can't upgrade for some reasons).我使用的是 C# 2.0 版(由于某些原因无法升级)。

Here are some examples;这里有些例子;

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

I have tried Regex("[^0-9]") which works if there is no character after digits (4th example)我试过 Regex("[^0-9]") 如果数字后没有字符(第四个例子)

 "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 [AZ] - 一个大写的 ASCII 字母
  • [0-9]+ - one or more ASCII digits. [0-9]+ - 一个或多个 ASCII 数字。

Alternatively, you might consider a ^[AZ][^AZ]+ pattern, where [^AZ]+ matches any one or more chars other than uppercase ASCII letters.或者,您可以考虑^[AZ][^AZ]+模式,其中[^AZ]+匹配除大写 ASCII 字母之外的任何一个或多个字符。

To ignore case, use RegexOptions.IgnoreCase : Regex.Match(text, @"^[AZ][0-9]+", RegexOptions.IgnoreCase) .要忽略大小写,请使用RegexOptions.IgnoreCaseRegex.Match(text, @"^[AZ][0-9]+", RegexOptions.IgnoreCase)

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

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