本文介绍了正则表达式拆分数字和字母组没有空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个类似11E12C108N的字符串,它是字母组和数字组的串联,我怎么拆分它们而中间没有分隔符空格字符?

If I have a string like "11E12C108N" which is a concatenation of letter groups and digit groups, how do I split them without a delimiter space character inbetween?

例如,我希望得到的分割为:

For example, I want the resulting split to be:

tokens[0] = "11"
tokens[1] = "E"
tokens[2] = "12"
tokens[3] = "C"
tokens[4] = "108"
tokens[5] = "N"

我现在有这个。

public static void main(String[] args) {

    String stringToSplit = "11E12C108N";

    Pattern pattern = Pattern.compile("\\d+\\D+");
    Matcher matcher = pattern.matcher(stringToSplit);

    while (matcher.find()) {
        System.out.println(matcher.group());
    }
}

这给了我:

11E
12C
108N

我可以让原始的正则表达式一次完成吗?而不是必须在中间令牌上再次运行正则表达式?

Can I make the original regex do a complete split in one go? Instead of having to run the regex again on the intermediate tokens?

推荐答案

使用以下正则表达式,并获取所有匹配项的列表。这将是你要找的。

Use the following regex, and get a list of all matches. That will be what you are looking for.

\d+|\D+

在Java中,我认为代码看起来像这样:

In Java, I think the code would look something like this:

Matcher matcher = Pattern.compile("\\d+|\\D+").matcher(theString);
while (matcher.find())
{
    // append matcher.group() to your list
}

这篇关于正则表达式拆分数字和字母组没有空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 22:20