【问题标题】:Complicated regex with numbers and group of numbers带有数字和数字组的复杂正则表达式
【发布时间】:2018-02-06 09:17:44
【问题描述】:

我有这样的字符串作为输入:

(1,3,4,(3,4,21),55,69,12,(3,8),9)

我想要这个输出,作为一个数组或一个字符串列表

1 - 3 - 4 - (3,4,21) - 55 - 69 - 12 - (3,8) - 9

有人可以帮忙吗?我尝试了几个正则表达式,但没有运气。

编辑:请注意,输出中的“-”表示同一数组或列表的不同元素,而不是所需的字符。

示例:数组[0]="1";数组[1]="3";数组[3]="(3,4,21)";

【问题讨论】:

  • 我建议不要为此使用正则表达式。
  • 是的……写一个解析器。
  • 输出中的 '-' 和 69 之间应该有空格吗?
  • 刚刚编辑了我的问题,感谢 Pzremyslaw Moskal

标签: java regex regex-lookarounds


【解决方案1】:

你可以试试这个正则表达式:

,(?!(?:(?:[^\(\)]*[\(\)]){2})*[^\(\)]*$)

这将匹配所有应该替换为 - 的逗号(,) 或者你也可以用上面的正则表达式分割

解释

逻辑是找逗号后面不跟偶数个括号( and )

Regex101 Demo

样本来源(run here):

final String regex = ",(?!(?:(?:[^\\(\\)]*[\\(\\)]){2})*[^\\(\\)]*$)";
final String string = "(1,3,4,(3,4,21),55,69,12,(3,8),9)";

String[] result=string.split(regex);
int len=result.length;
for(int i=0;i<len;i++)
{

// the following two if condition is necessary to remove the start and end brace
// many other and probably better alternatives could be there to remove it 

 if(result[i].contains("(") && !result[i].contains(")"))
  result[i]=result[i].replace("(","");
 else if(result[i].contains(")") && !result[i].contains("("))
  result[i]=result[i].replace(")","");   
}

System.out.println(java.util.Arrays.toString(result));

输出:

[1, 3, 4, (3,4,21), 55, 69, 12, (3,8), 9]

【讨论】:

    猜你喜欢
    • 2016-07-08
    • 1970-01-01
    • 1970-01-01
    • 2018-06-27
    • 1970-01-01
    • 1970-01-01
    • 2012-08-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多