使用正则表达式删除括号内的特定字符 [英] Remove specific characters inside parentheses using regex

查看:144
本文介绍了使用正则表达式删除括号内的特定字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的一行:

BlockedMatch(XA, YB), Correlation(XA, QC), Correlation(YB, QC), Correlation(QC, YB)

我希望它看起来像这样:

I want it to look like this:

BlockedMatch(XAYB), Correlation(XAQC), Correlation(YBQC), Correlation(QCYB)

我不能只对,进行替换,因为它会删除括号外的那些实例。

I can't just do a replace on ", " because it will remove those instances that exist outside of the parentheses.

我试过这个:

replaceAll("\\((.*?)\\)", "")

取代所有内容在括号内(不只是逗号)。我试图将逗号和空格组合添加到该正则表达式中,但它似乎没有删除任何内容。

which replaces everything inside the parentheses (not just the comma). I've tried to add just the comma and space combination into that regex, but it doesn't seem to remove anything then.

有人可以告诉我如何指定只有当在括号内 时才会删除(逗号空格)?

Could someone show me how to specify to only remove the ", " (comma-space) when it occurs inside parentheses?

推荐答案

使用前瞻:

str = str.replaceAll(", (?=[^(]*\\))", "");

此正则表达式仅当下一个括号字符是<​​em>时才替换逗号空格括号

This regex says "replace the comma-space only when the next bracket character is a close bracket"

一些测试代码:

String str = "BlockedMatch(XA, YB), Correlation(XA, QC), Correlation(YB, QC), Correlation(QC, YB)";
str = str.replaceAll(", (?=[^(]*\\))", "");
System.out.println(str);

输出:

BlockedMatch(XAYB), Correlation(XAQC), Correlation(YBQC), Correlation(QCYB)

这篇关于使用正则表达式删除括号内的特定字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆