【发布时间】:2021-03-06 20:18:13
【问题描述】:
如何在不消耗拆分器部分的情况下拆分字符串?
像这样的东西,但: 我使用的是#[a-fA-F0-9]{6} 正则表达式。
String from = "one:two:three";
String[] to = ["one",":","two",":","three"];
我已经尝试过使用 commons lib,因为它有 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.
【问题讨论】: