基于数字/字符模式拆分字符串 - Java

时间:2016-02-23 15:46:30

标签: java regex string

我想用以下模式拆分字符串:

abc3xab     -> ('abc', '3xa', 'b')
abc3x3xab   -> ('abc', '3x3x', 'ab')
abc3xxab    -> ('abc', '3xx', 'ab')
abc34xxab   -> ('abc', '34xx', 'ab')
abc100ab    -> ('abc100ab')
abc10axb    -> ('abc10axb')

就是这样,模式是'[0-9] + x [a-z]'(如果有一个数字后跟'x'a-z之间的任何字符。 我试过了

String[] words = string.split("[0-9]+x")

然后我只有abcab。这样做的正确方法是什么?

1 个答案:

答案 0 :(得分:2)

尝试使用正向前瞻和后瞻的组合来保留分隔符:

String[] words = string.split("((?<=[0-9]+x)|(?=[0-9]+x))");

Sample IDEONE demo

String[] words = "abc3xab".split("((?<=[0-9]+x)|(?=[0-9]+x))");
System.out.println(Arrays.toString(words));
String[] words1 = "abc3xxab".split("((?<=[0-9]+x)|(?=[0-9]+x))");
System.out.println(Arrays.toString(words1));
String[] words2 = "abc34xxab".split("((?<=[0-9]+x)|(?=[0-9]+x))");
System.out.println(Arrays.toString(words2));
String[] words3 = "abc100ab".split("((?<=[0-9]+x)|(?=[0-9]+x))");
System.out.println(Arrays.toString(words3));
String[] words4 = "abc10axb".split("((?<=[0-9]+x)|(?=[0-9]+x))");
System.out.println(Arrays.toString(words4));

结果:

[abc, 3x, ab]
[abc, 3x, xab]
[abc, 3, 4x, xab]
[abc100ab]
[abc10axb]