简体   繁体   English

用正则表达式拆分 JAVA 不起作用

[英]JAVA split with regex doesn't work

I have the following String 46MTS007 and i have to split numbers from letters so in result i should get an array like {"46", "MTS", "007"}我有以下字符串46MTS007 ,我必须从字母中拆分数字,因此结果我应该得到一个数组,如{"46", "MTS", "007"}

String s = "46MTS007";
String[] spl = s.split("\\d+|\\D+");

But spl remains empty, what's wrong with the regex?但是spl仍然是空的,正则表达式有什么问题? I've tested in regex101 and it's working like expected (with global flag)我已经在 regex101 中进行了测试,它按预期工作(带有全局标志)

If you want to use split you can use this lookaround based regex:如果你想使用 split 你可以使用这个基于环视的正则表达式:

(?<=\d)(?=\D)|(?<=\D)(?=\d)

RegEx Demo正则表达式演示

Which means split the places where next position is digit and previous is non-digit OR when position is non-digit and previous position is a digit.这意味着拆分下一个位置是数字和前一个位置是非数字的位置,或者当位置是非数字并且前一个位置是一个数字时。

In Java:在 Java 中:

String s = "46MTS007";
String[] spl = s.split("(?<=\\d)(?=\\D)|(?<=\\D)(?=\\d)");

Regex you're using will not split the string.您使用的正则表达式不会拆分字符串。 Split() splits the string with regex you provide but regex used here matches with whole string not the delimiter. Split() 使用您提供的正则表达式拆分字符串,但此处使用的正则表达式匹配整个字符串而不是分隔符。 You can use Pattern Matcher to find different groups in a string.您可以使用模式匹配器在字符串中查找不同的组。

public static void main(String[] args) {
    String line = "46MTS007";
    String regex = "\\D+|\\d+";
    Pattern pattern = Pattern.compile(regex);
    Matcher m  = pattern.matcher(line);    
    while(m.find())
        System.out.println(m.group());
}

Output:输出:

46
MTS
007

Note: Don't forget to user m.find() after capturing each group otherwise it'll not move to next one.注意:在捕获每个组后不要忘记用户 m.find() 否则它不会移动到下一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM