得到一个字符串
:
String s = "1+2*(30+4/2-(1+2))*2+1";
得到了分割字符串的方法
:
public void convertString(String s) {
String[] arr = s.split("(?<=[\\d.])(?=[^\\d.])|(?<=[^\\d.])(?=[\\d.])");
}
问题是:
Output:
[1, +, 2, *(, 30, +, 4, /, 2, -(, 1, +, 2, ))*, 2, +, 1]
//here round brackets store in the same cell with next symbol or prev symbol *(, ))*,
预期输出:
[1, +, 2, *, (, 30, +, 4, /, 2, -, (, 1, +, 2, ), ), *, 2, +, 1]
// here round brackets store in a separate arr cells
我需要在单独的数组单元格中存储圆括号。
如何实现?
最佳答案
您的正则表达式实际上在从非数字到数字的任何位置拆分,反之亦然。它明确不会在非数字之间拆分。
所以给出你当前的方法,修复方法是
public void convertString(String s) {
String[] arr = s.split("(?<=[\\d.])(?=[^\\d.])|(?<=[^\\d.])(?=[^\\d.])|(?<=[^\\d.])(?=[\\d.])");
}
也就是说,这可能是更好的方法。一个简单的正则表达式匹配,其中表达式要么是单个非数字,要么是一组急切的数字,已经比这更容易了。
关于java - 如何拆分带有圆括号的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64753249/