我试图用特殊字符分割字符串,但不能正确分割括号。 这是我正在尝试的代码:
class Ione
{
public static void main (String[] args) throws java.lang.Exception
{
String str = "g, i+, w+ | (d | (u+, f))+";
String[] chunks = str.split(",\\s+|(?=\\W)");
for(int q=0; q<chunks.length; q++) {
System.out.println(""+chunks[q]);
}
}
}
正则表达式不会拆分起始括号(
我正在尝试获得以下输出:
g,i,+,w,+,|,(,d,|,(,u,+,f,),),+
有人可以帮助我吗?谢谢。
答案 0 :(得分:3)
因此,您想使用split()
来分别获取每个字符(空格和逗号除外),因此请按空格/逗号和“无”(即非空格/之间的零宽度“空格”)进行分隔逗号字符。
String str = "g, i+, w+ | (d | (u+, f))+";
String[] chunks = str.split("[\\s,]+|(?<![\\s,])(?![\\s,])");
System.out.println(String.join(",", chunks));
输出
g,i,+,w,+,|,(,d,|,(,u,+,f,),),+
替代项::搜索所需内容,并将其收集到数组或List
(需要Java 9)中:
String str = "g, i+, w+ | (d | (u+, f))+";
String[] chunks = Pattern.compile("[^\\s,]").matcher(str).results()
.map(MatchResult::group).toArray(String[]::new);
System.out.println(String.join(",", chunks));
相同的输出。
对于Java的旧版本,请使用find()
循环:
String str = "g, i+, w+ | (d | (u+, f))+";
List<String> chunkList = new ArrayList<>();
for (Matcher m = Pattern.compile("[^\\s,]").matcher(str); m.find(); )
chunkList.add(m.group());
System.out.println(chunkList);
输出
[g, i, +, w, +, |, (, d, |, (, u, +, f, ), ), +]
您始终可以将List
转换为数组:
String[] chunks = chunkList.toArray(new String[0]);