如何使用正则表达式分割字符串而不消耗分割符部分?

4
我如何在不消耗分隔符的情况下拆分字符串?类似这样,但是我使用的是#[a-fA-F0-9]{6}正则表达式,而不是:
String from = "one:two:three";
String[] to  = ["one",":","two",":","three"];

我已经尝试使用commons库,因为它有StringUtils.splitPreserveAllTokens()函数,但它不能与正则表达式一起使用。

编辑:我想我应该更明确一些,但这就是我所寻找的。

String string = "Some text here #58a337test #a5fadbtest #123456test as well.
 #58a337Word#a5fadbwith#123456more hex codes.";

String[] parts = string.split("#[a-fA-F0-9]{6}");
/*Output: ["Some text here ","#58a337","test ","#a5fadb","test ","#123456","test as well. ",
"#58a337","Word","#a5fadb","with","#123456","more hex codes."]*/

编辑2:解决方案!

final String string = "Some text here #58a337test #a5fadbtest #123456test as
 well. #58a337Word#a5fadbwith#123456more hex codes.";

String[] parts = string.split("(?=#.{6})|(?<=#.{6})");
for(String s: parts) {
    System.out.println(s);
}

输出:

Some text here 
#58a337
test 
#a5fadb
test 
#123456
test as well. 
#58a337
Word
#a5fadb
with
#123456
more hex codes.
2个回答

5
您可以使用\\b (单词边界,\ 转义)来拆分您的情况,
final String string = "one:two:three";
    
String[] parts = string.split("\\b");
for(String s: parts) {
    System.out.println(s);
}

在线试用!


1
这对于 : 是有效的,但我需要它适用于这个正则表达式 #[a-fA-F0-9]{6}。我现在已经编辑了帖子,使其更加准确。 - Lynx
1
@Lynx - 然后使用 (?=#.{6})|(?<=#.{6}) 作为分隔符,跟着 Tim 去。 - vrintle

4

@vrintle +1 给出的答案可能是对您的确切输入编写的最紧凑的代码。但是,假设除了 : 之外,您的输入中可能还有其他非单词字符,则您也可以使用环视进行更精确的拆分:

String from = "one:two:three";
String[] parts = from.split("(?<=:)|(?=:)");
System.out.println(Arrays.toString(parts));

这将输出:
[one, :, two, :, three]

1
哦,这太美了! - Eugene
1
@Eugene 别这样!你让我害羞了 :-) - Tim Biegeleisen
我修改了帖子,因为它并不完全准确地反映了我所需要的。而@vrintle评论了我确切需要的内容。但还是谢谢。 :) - Lynx

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