Lyn*_*ynx 4 java regex arrays split
如何在不消耗拆分器部分的情况下拆分字符串?
像这样的东西,但:我使用的是#[a-fA-F0-9]{6}正则表达式。
String from = "one:two:three";
String[] to = ["one",":","two",":","three"];
Run Code Online (Sandbox Code Playgroud)
我已经尝试过使用 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."]*/
Run Code Online (Sandbox Code Playgroud)
编辑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);
}
Run Code Online (Sandbox Code Playgroud)
输出:
Some text here
#58a337
test
#a5fadb
test
#123456
test as well.
#58a337
Word
#a5fadb
with
#123456
more hex codes.
Run Code Online (Sandbox Code Playgroud)
您可以使用\\b(word-break, \escaped) 在您的情况下拆分,
final String string = "one:two:three";
String[] parts = string.split("\\b");
for(String s: parts) {
System.out.println(s);
}
Run Code Online (Sandbox Code Playgroud)