我如何在不消耗分隔符的情况下拆分字符串?类似这样,但是我使用的是
#[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.
:
是有效的,但我需要它适用于这个正则表达式#[a-fA-F0-9]{6}
。我现在已经编辑了帖子,使其更加准确。 - Lynx(?=#.{6})|(?<=#.{6})
作为分隔符,跟着 Tim 去。 - vrintle