How can I split a string such as "Mar10" into "Mar" and "10" in c#? The format of the string will always be letters then numbers so I can use the first instance of a number as an indicator for where to split the string.
如何在c#中将“Mar10”等字符串拆分为“Mar”和“10”?字符串的格式将始终是字母然后是数字,因此我可以使用数字的第一个实例作为分割字符串的位置的指示符。
4 个解决方案
#1
14
You could do this:
你可以这样做:
var match = Regex.Match(yourString, "(\w+)(\d+)");
var month = match.Groups[0].Value;
var day = int.Parse(match.Groups[1].Value);
#2
5
You are not saying it directly, but from your example it seems are you just trying to parse a date.
你不是直接说,但从你的例子来看,你似乎只是想解析一个约会。
If that's true, how about this solution:
如果这是真的,那么这个解决方案怎么样:
DateTime date;
if(DateTime.TryParseExact("Mar10", "MMMdd", new CultureInfo("en-US"), DateTimeStyles.None, out date))
{
Console.WriteLine(date.Month);
Console.WriteLine(date.Day);
}
#3
3
char[] array = "Mar10".ToCharArray();
int index = 0;
for(int i=0;i<array.Length;i++)
{
if (Char.IsNumber(array[i]){
index = i;
break;
}
}
Index will indicate split position.
索引将指示拆分位置。
#4
1
var match = Regex.Match(yourString, "([|A-Z|a-z| ]*)([\d]*)");
var month = match.Groups[1].Value;
var day = int.Parse(match.Groups[2].Value);
I tried Konrad's answer above, but it didn't quite work when I entered it into RegexPlanet. Also the Groups[0
] returns the whole string Mar10
. You want to start with Groups[1]
, which should return Mar
and Groups[2]
should return 10
.
我在上面尝试了康拉德的答案,但是当我进入RegexPlanet时,它并没有完全奏效。 Group [0]也返回整个字符串Mar10。你想从群组[1]开始,群组[1]应返回3月,群组[2]应返回10。
#1
14
You could do this:
你可以这样做:
var match = Regex.Match(yourString, "(\w+)(\d+)");
var month = match.Groups[0].Value;
var day = int.Parse(match.Groups[1].Value);
#2
5
You are not saying it directly, but from your example it seems are you just trying to parse a date.
你不是直接说,但从你的例子来看,你似乎只是想解析一个约会。
If that's true, how about this solution:
如果这是真的,那么这个解决方案怎么样:
DateTime date;
if(DateTime.TryParseExact("Mar10", "MMMdd", new CultureInfo("en-US"), DateTimeStyles.None, out date))
{
Console.WriteLine(date.Month);
Console.WriteLine(date.Day);
}
#3
3
char[] array = "Mar10".ToCharArray();
int index = 0;
for(int i=0;i<array.Length;i++)
{
if (Char.IsNumber(array[i]){
index = i;
break;
}
}
Index will indicate split position.
索引将指示拆分位置。
#4
1
var match = Regex.Match(yourString, "([|A-Z|a-z| ]*)([\d]*)");
var month = match.Groups[1].Value;
var day = int.Parse(match.Groups[2].Value);
I tried Konrad's answer above, but it didn't quite work when I entered it into RegexPlanet. Also the Groups[0
] returns the whole string Mar10
. You want to start with Groups[1]
, which should return Mar
and Groups[2]
should return 10
.
我在上面尝试了康拉德的答案,但是当我进入RegexPlanet时,它并没有完全奏效。 Group [0]也返回整个字符串Mar10。你想从群组[1]开始,群组[1]应返回3月,群组[2]应返回10。