简体   繁体   English

如何在 RegExp javascript 中放置 [](方括号)?

[英]How can I put [] (square brackets) in RegExp javascript?

I'm trying this:我正在尝试这个:

str = "bla [bla]";
str = str.replace(/\\[\\]/g,"");
console.log(str);

And the replace doesn't work, what am I doing wrong?而且替换不起作用,我做错了什么?

UPDATE : I'm trying to remove any square brackets in the string, what's weird is that if I do更新:我正在尝试删除字符串中的任何方括号,奇怪的是,如果我这样做了

replace(/\[/g, '')
replace(/\]/g, '')

it works, but它有效,但是
replace(/\\[\\]/g, '');
doesn't.没有。

It should be:它应该是:

str = str.replace(/\[.*?\]/g,"");

You don't need double backslashes (\\) because it's not a string but a regex statement, if you build the regex from a string you do need the double backslashes ;).您不需要双反斜杠 (\\),因为它不是字符串而是正则表达式语句,如果您从字符串构建正则表达式,则确实需要双反斜杠 ;)。

It was also literally interpreting the 1 (which wasn't matching).它也从字面上解释了 1(不匹配)。 Using .* says any value between the square brackets.使用.*表示方括号之间的任何值。

The new RegExp string build version would be:新的 RegExp 字符串构建版本将是:

str=str.replace(new RegExp("\\[.*?\\]","g"),"");

UPDATE: To remove square brackets only:更新:仅删除方括号:

str = str.replace(/\[(.*?)\]/g,"$1");

Your above code isn't working, because it's trying to match "[]" (sequentially without anything allowed between).您上面的代码不起作用,因为它试图匹配“[]”(顺序不允许任何东西)。 We can get around this by non-greedy group-matching ( (.*?) ) what's between the square brackets, and using a backreference ( $1 ) for the replacement.我们可以通过非贪婪的组匹配( (.*?) )方括号之间的内容来解决这个问题,并使用反向引用( $1 )进行替换。

UPDATE 2: To remove multiple square brackets更新 2:删除多个方括号

str = str.replace(/\[+(.*?)\]+/g,"$1");
// bla [bla] [[blaa]] -> bla bla blaa
// bla [bla] [[[blaa] -> bla bla blaa

Note this doesn't match open/close quantities, simply removes all sequential opens and closes.请注意,这与打开/关闭数量不匹配,只是删除所有顺序打开和关闭。 Also if the sequential brackets have separators (spaces etc) it won't match.此外,如果连续括号有分隔符(空格等),它将不匹配。

You have to escape the bracket, like \\[ and \\] .您必须转义括号,例如\\[\\] Check out http://regexpal.com/ .查看http://regexpal.com/ It's pretty useful :)它非常有用:)

To replace all brackets in a string, this should do the job:要替换字符串中的所有括号,这应该可以完成以下工作:

str.replace(/\[|\]/g,'');

I hope this helps.我希望这有帮助。
Hristo赫里斯托

Here's a trivial example but worked for me.这是一个微不足道的例子,但对我有用。 You have to escape each sq bracket, then enclose those brackets within a bracket expression to capture all instances.您必须转义每个方括号,然后将这些方括号括在方括号表达式中以捕获所有实例。

 const stringWithBrackets = '[]]][[]]testing][[]]['; const stringWithReplacedBrackets = stringWithBrackets.replace(/[\\[\\]]/g, ''); console.log(stringWithReplacedBrackets);

I stumbled on this question while dealing with square bracket escaping within a character class that was designed for use with password validation requiring the presence of special characters.我在处理一个字符类中的方括号转义时偶然发现了这个问题,该字符类旨在用于需要存在特殊字符的密码验证。

Note the double escaping:注意双重转义:

var regex = new RegExp('[\\\\]]');

As @rudu mentions, this expression is within a string so it must be double escaped.作为@rudu提到,这种表达一个字符串中,因此必须进行双重转义。 Note that the quoting type (single/double) is not relevant here.请注意,引用类型(单/双)在这里不相关。

Here is an example of using square brackets in a character class that tests for all the special characters found on my keyboard:这里是一个字符类,对所有特殊字符的测试我的键盘上找到的用方括号的例子:

var regex = new RegExp('[-,_,\',",;,:,!,@,#,$,%,^,&,*,(,),[,\\],\?,{,},|,+,=,<,>,~,`,\\\\,\,,\/,.]', 'g')

How about the following?以下情况如何?

str = "bla [bla]";

str.replace(/[[\\]]/g,'');

You create a character set with just the two characters you are interested in and do a global replace.您只使用您感兴趣的两个字符创建一个字符集并进行全局替换。

Two backslashes produces a single backslash, so you're searching for "a backslash, followed by a character class consisting of a 1 or a right bracket , and then you're missing an closing bracket.两个反斜杠产生一个反斜杠,因此您正在搜索“一个反斜杠,后跟由1right bracket组成的字符类,然后您缺少一个right bracket括号。

Try尝试

str.replace(/\[1\]/g, '');

What exactly are you trying to match?你到底想匹配什么?

If you don't escape the brackets, they are considered character classes.如果您不转义括号,它们将被视为字符类。 This:这个:

/[1\\]/

Matches either a 1 or a backslash.匹配 1 或反斜杠。 You may want to escape them with one backslash only:您可能只想用一个反斜杠来转义它们:

/\[1\]/

But this won't match either, as you don't have a [1] in your string.但这也不匹配,因为您的字符串中没有[1]

Nobody quite made it simple and correct:没有人让它变得简单和正确:

str.replace(/[[\]]/g, '');

Note the use of a character class, with no escape for the open bracket, and a single backslash escape for the close bracket.请注意使用字符类,左括号没有转义,右括号有单个反斜杠转义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM