3 回答
TA贡献1895条经验 获得超7个赞
要使用逗号分隔,后跟字母数字字符,您可以使用
String pattern = ",(?=\\p{Alnum})";
或者,如果您计划支持任何 Unicode 字母,请在模式旁边传递Pattern.UNICODE_CHARACTER_CLASS
( ) 选项:(?U)
String pattern = "(?U),(?=\\p{Alnum})";
请参阅RegexPlanet 正则表达式演示。
Java演示:
String s = "hello,world,good day to you, Sir,test,1,2";
String[] result = s.split(",(?=\\p{Alnum})");
for (String r:result) {
System.out.println(r);
}
输出:
hello
world
good day to you, Sir
test
1
2
TA贡献1864条经验 获得超2个赞
在此链接中,有一个答案解释了Lookahead 和 Lookbehind的使用。在这里我留下一个我相信可以解决你描述的问题的代码:
private static String[] mySplit(final String line, final char separator) {
String regex = "((?<=(" + separator + "\\w)|(?=(" + separator + "\\w))))";
String[] split = line.split(regex);
List<String> list = new ArrayList<>();
for (int i = 0; i < split.length; i++) {
String token = split[i];
if (token.startsWith(String.valueOf(separator))) {
split[i + 1] = token.substring(1) + split[i + 1];
} else {
list.add(token);
}
}
return list.toArray(new String[list.size()]);
}
private static String concatenate(final String[] tokens, final char separator){
StringBuilder builder = new StringBuilder();
for (int i = 0; i < tokens.length; i++) {
builder.append(tokens[i]).append((i < tokens.length - 1) ? separator : "");
}
return builder.toString();
}
public static void main(String[] args) {
final String line = "hello,world,good day to you, Sir,test";
final String[] tokens = mySplit(line, ',');
final String newLine = concatenate(tokens, '|');
System.out.println("newLine = " + newLine);
}
添加回答
举报