C# 如何使用正则表达式将字符串拆分为数字和字母
我想将像“001A”这样的字符串拆分为“001”和“a”您可以尝试这样的方法从字符串中检索整数:C# 如何使用正则表达式将字符串拆分为数字和字母,c#,regex,C#,Regex,我想将像“001A”这样的字符串拆分为“001”和“a”您可以尝试这样的方法从字符串中检索整数: StringBuilder sb = new StringBuilder(); Regex regex = new Regex(@"\d*"); MatchCollection matches = regex.Matches(inputString); for(int i=0; i < matches.count;i++){ sb.Append(matches[i].value + "
StringBuilder sb = new StringBuilder();
Regex regex = new Regex(@"\d*");
MatchCollection matches = regex.Matches(inputString);
for(int i=0; i < matches.count;i++){
sb.Append(matches[i].value + " ");
}
StringBuilder sb=新建StringBuilder();
正则表达式正则表达式=新正则表达式(@“\d*”);
MatchCollection matches=regex.matches(inputString);
for(int i=0;i
然后更改正则表达式以匹配字符并执行相同的循环。如果您的代码与001A示例一样简单|复杂,则不应使用正则表达式,而应使用for循环。如果更像
001A002B
,则可以
var s = "001A002B";
var matches = Regex.Matches(s, "[0-9]+|[A-Z]+");
var numbers_and_alphas = new List<string>();
foreach (Match match in matches)
{
numbers_and_alphas.Add(match.Value);
}
var s=“001A002B”;
var matches=Regex.matches,“[0-9]+|[A-Z]+”;
变量编号和字母=新列表();
foreach(匹配中的匹配)
{
数字和字母相加(匹配值);
}
这是Java,但它应该可以翻译成其他风格,只需很少修改
String s = "123XYZ456ABC";
String[] arr = s.split("(?<=\\d)(?=\\D)|(?<=\\D)(?=\\d)");
System.out.println(Arrays.toString(arr));
// prints "[123, XYZ, 456, ABC]"
String s=“123XYZ456ABC”;
String[]arr=s.split((?String.split)据我所知不接受正则表达式。您测试过吗?它应该是regex.split(“001A”,“a-Z])”)
,或者组被删除(作为分隔符)。这是可行的,但它提供了一个包含3个元素的字符串数组。最后一个元素为空。
匹配任何内容,您应该限制为\w
或[a-zA-Z]
@knittl-我知道,
是可以的,只要OP不需要验证它。这个问题没有足够的细节,所以我选择了这个问题。问题的标题是»如何拆分数字和字母«;),但无论如何,在给定的示例中,您的解决方案将给出正确的结果
var s = "001A002B";
var matches = Regex.Matches(s, "[0-9]+|[A-Z]+");
var numbers_and_alphas = new List<string>();
foreach (Match match in matches)
{
numbers_and_alphas.Add(match.Value);
}
String s = "123XYZ456ABC";
String[] arr = s.split("(?<=\\d)(?=\\D)|(?<=\\D)(?=\\d)");
System.out.println(Arrays.toString(arr));
// prints "[123, XYZ, 456, ABC]"