![](/img/trans.png)
[英]JavaFx : how to split a string and also display the splitting character on the UI (“:”)
[英]Splitting the string, integer and also the special character (“_”)
我试图在字符串,整数和特殊字符之间进行分割,我尝试了一些方法,但是对我来说不起作用,所以对它有任何想法吗?
源代码:
String a = "abc1_xyz1";
String[] qq = a.split("(?<=\\d)(?=\\D)|(?<=\\D)(?=\\d)|('_')");
for(int i=0; i<qq.length; i++){
System.out.println(qq[i] + " \n");
}
我的期望输出是:
abc
1
_
xyz
1
但我得到的是:
abc
1
_xyz
1
这里有人可以给我指导吗?
你有几个小问题。 \\ D将匹配_并且您不希望在您的代码中同样,在_上拆分将从输出中排除它。
这段代码可行
String a = "abc1_xyz1";
for (String s : a.split("" +
"(?<=[a-z])(?=\\d)" + // space between letter and digit
"|(?<=\\d)(?=[a-z])" + // space between digit and letter
"|(?<=_)(?=\\d)" + // space between _ and digit
"|(?<=\\d)(?=_)" + // space between digit and _
"|(?<=_)(?=[a-z])" + // space between _ and letter
"|(?<=[a-z])(?=_)" + // space between letter and _
"")) {
System.out.println(s);
}
我认为split()
是错误的方法,因为你没有任何分隔符,并且想要使用分割的所有内容(它在值之间给出空行)。
相反,假设表达式是常规的,我会使用Pattern.compile()
和Matcher.group()
,如下:
String a = "abc1_xyz1";
Pattern p = Pattern.compile("(\\D+)(\\d+)(_)(\\D+)(\\d+)");
Matcher m = p.matcher(a);
if (m.find()) {
for (int i = 1; i<=m.groupCount();i++) {
System.out.println(m.group(i));
}
}
如果任何组是可选的,您可以在其后面添加一个问号(然后该组将为空)。
另一种解决方案:在检查数字/非数字边界之前检查_
:
String[] qq = a.split("(_)|(?<=\\d)(?=\\D)|(?<=\\D)(?=\\d)");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.