如何在 java 中使用分隔符 '(' '{' '} ')'' 拆分字符串

how to split a string with delimeters '(' '{' '} ')'' in java

String str = "one(two)three{four}"
String[] arr  = str.split("(\()(\{)(\))(\}))";

输出应该是这样的:

arr = {"one","two","three","four"};

正则表达式无法编译。

 ( \( )                        # (1)
 ( \{ )                        # (2)
 ( \) )                        # (3)
 ( \} )                        # (4)
 =    )  <-- Unbalanced  ')'

您可能打算在 [(){}]+

上拆分

你应该转义反斜杠 and 添加或:

String str = "one(two)three{four}";    
String[] arr = str.split("\(|\)|\{|\}");

或者您可以使用方括号列表:

String str = "one(two)three{four}";    
String[] arr = str.split("[(){}]");

两个选项都可以

如果你只想捕获上面字符串中的文本部分,你可以使用下面的正则表达式;

(\w+)

Link 测试 here