如何使用正则表达式将字符串分割为数字和字母

3
我想将类似于“001A”的字符串拆分成“001”和“A”。
6个回答

4
Match match = Regex.Match(s, @"^(\d+)(.+)$");
string numeral = match.Groups[1].Value;
string tail = match.Groups[2].Value;

". 匹配任何字符,您应该限制为 \w[a-zA-Z]。" - knittl
@knittl - 我知道,只要 OP 不需要验证它,就可以了。由于问题没有足够的细节,所以我选择了这个方案。 - Kobi
如何拆分数字和字母? ;) 但是不要紧,在给定的示例中,您的解决方案将给出正确的结果。 - knittl

4
string[] data = Regex.Split("001A", "([A-Z])");
data[0] -> "001"
data[1] -> "A"

1
据我所知,String.Split不接受正则表达式。 - Kobi
1
你测试过了吗?应该是 Regex.Split("001A", "([A-Z])"),或者将组移除(作为分隔符)。 - Kobi
这个可以运行,但是它返回一个包含3个元素的字符串数组。最后一个元素为空。 - user99322

2
这是Java,但只需稍作修改即可将其翻译为其他语言版本。
    String s = "123XYZ456ABC";
    String[] arr = s.split("(?<=\\d)(?=\\D)|(?<=\\D)(?=\\d)");
    System.out.println(Arrays.toString(arr));
    // prints "[123, XYZ, 456, ABC]"

正如您所看到的,这将在\d后跟\D或反之处分割字符串。它使用正向和负向环视来查找拆分位置。


1
如果你的代码像你的001A示例一样简单|复杂,那么你不应该使用正则表达式而是使用for循环。

0
你可以尝试像这样从字符串中检索整数:
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 + " ");
}

然后将正则表达式更改为匹配字符并执行相同的循环。


0

而且如果有更多类似 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);
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接