Javascript 正则表达式转义括号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10326887/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:52:39  来源:igfitidea点击:

Regex to escape the parentheses

javascriptregex

提问by RoundOutTooSoon

I tried different ways to escape the parentheses using regex in JavaScript but I still can't make it work.

我尝试了不同的方法来使用 JavaScript 中的正则表达式来转义括号,但我仍然无法使其工作。

This is the string:

这是字符串:

"abc(blah (blah) blah()...).def(blah() (blah).. () ...)"

I want this to be detected:

我希望检测到这一点:

abc().def() 

Using this code, it returns false.

使用此代码,它返回 false。

 str.match(/abc\([^)]*\)\.def\([^)]*\)/i);

Can you please tell me why my regex is not working?

你能告诉我为什么我的正则表达式不起作用吗?

采纳答案by alan

This regex will match the string you provided:

此正则表达式将匹配您提供的字符串:

(abc\().+(\)\.def\().+(\))

And using backreferences $1$2$3will produce abc().def()

并且使用反向引用$1$2$3会产生abc().def()

Or just use this if you don't want the back references:

或者,如果您不想要反向引用,请使用它:

abc\(.+\)\.def\(.+\)

回答by LearningDeveloper

K... Here's an Idea...

K...这是一个想法...

abc(blah (blah) blah()).def(blah() (blah).blah())

Use regExp like this

像这样使用正则表达式

var regExp1 = \^([a-z])*\(\ig;

it'll match

它会匹配

abc(

then use

然后使用

var regExp2 = /\)\./

it'll match the

它会匹配

")." 

in the string..

在字符串中..

then split the actual string so that it becomes

然后拆分实际的字符串,使其成为

def(blah() (blah).blah())

repeat till the regular expression can't find the

重复直到正则表达式找不到

regExp2 

and add a closing bracket.. The simplest solution I could think of.. Hope it helps..

并添加一个结束括号..我能想到的最简单的解决方案..希望它有帮助..