如何根据字母和数字在C#中拆分字符串

Add*_*die 10 c# regex string

如何在c#中将"Mar10"等字符串拆分为"Mar"和"10"?字符串的格式将始终是字母然后是数字,因此我可以使用数字的第一个实例作为分割字符串的位置的指示符.

Kon*_*lph 14

你可以这样做:

var match = Regex.Match(yourString, "(\w+)(\d+)");
var month = match.Groups[0].Value;
var day = int.Parse(match.Groups[1].Value);
Run Code Online (Sandbox Code Playgroud)


Ser*_*jev 5

你不是直接说,但从你的例子来看,你似乎只是想解析一个约会.

如果这是真的,那么这个解决方案怎么样:

DateTime date;
if(DateTime.TryParseExact("Mar10", "MMMdd", new CultureInfo("en-US"), DateTimeStyles.None, out date))
{
    Console.WriteLine(date.Month);
    Console.WriteLine(date.Day);
}
Run Code Online (Sandbox Code Playgroud)


小智 5

var match = Regex.Match(yourString, "([|A-Z|a-z| ]*)([\d]*)");
var month = match.Groups[1].Value;
var day = int.Parse(match.Groups[2].Value);
Run Code Online (Sandbox Code Playgroud)

我尝试了上面康拉德的答案,但当我将其输入 RegexPlanet 时,它并没有完全起作用。此外Groups[0] 返回整个字符串Mar10。你想从 , 开始Groups[1],它应该返回Mar并且Groups[2]应该返回10