简体   繁体   English

具有右方括号字符的javascript match方法

[英]javascript match method with a closing square bracket character

How can I use a closing square bracket as a character in a javascript regular expression? 如何在JavaScript正则表达式中使用右方括号作为字符?

"Acb[".match('[\(, \), \[]')

returns: 返回:

["["]

But when I add the closing square bracket as a character it does not work : 但是当我添加右方括号作为字符时,它不起作用:

"Acb[".match('[\(, \), \[, \]]')
null


"Acb]".match('[\(, \), \[, \]]')
null

"Acb]".match(/[\\(, \\), \\[, \\]]/) returns ["]"] . "Acb]".match(/[\\(, \\), \\[, \\]]/)返回["]"] You should use / instead of a quotation mark to denote a regex to avoid problems with escaping 您应使用/而不是引号来表示正则表达式,以避免转义问题

You also dont need to escape most of those characters. 您也不需要转义大多数字符。 "Acb]".match(/[()[, \\]]/) will match (, ), [, ], a comma, or a space "Acb]".match(/[()[, \\]]/)将匹配(,),[,],逗号或空格

Info on character classes can be found here 字符类的信息可以在这里找到

@wolffer-east's answer is correct. @ wolffer-east的答案是正确的。 I'm posting just to explain why his/her answer works. 我发布的只是为了解释他/她的答案为何有效。

According to MDN , the argument to String.prototype.match can be a string rather than a regex: 根据MDNString.prototype.match的参数可以是字符串,而不是正则表达式:

Parameters 参量

regexp 正则表达式

A regular expression object. 正则表达式对象。 If a non-RegExp object obj is passed, it is implicitly converted to a RegExp by using new RegExp(obj). 如果传递了非RegExp对象obj,则使用新的RegExp(obj)将其隐式转换为RegExp。

So it's not immediately obvious why using slashes to delimit the regex works, while using quotes doesn't. 因此,为什么使用斜杠来分隔正则表达式有效而使用引号却不可行,目前尚不清楚。 The reason is that the two delimitation forms treat backslash-escaping differently. 原因是两种定界形式对反斜杠转义的处理不同。 When you write 当你写

"Acb[".match('[\(, \), \[, \]]')

The quotes apply the backslash-escaping first, before any regex is created. 在创建任何正则表达式之前,引号首先应用反斜杠转义。 Since backslash-parentheses and backslash-bracket are not special escape sequences, they translate to just parentheses and bracket, respectively. 由于反斜杠括号和反斜杠括号不是特殊的转义序列,因此它们分别转换为仅括号和方括号。 Thus this: 因此:

'[\(, \), \[, \]]'

is equivalent to this: 等效于此:

'[(, ), [, ]]'

It's only after that that the RegExp constructor is invoked. 只有在此之后,才调用RegExp构造函数。 At this point the closing bracket is no longer escaped, and is treated as the ending marker for the character class rather than a character within the class. 此时,右括号不再被转义,并且被视为字符类的结束标记,而不是该类中的字符。 You can avoid this by escaping the backslash itself: 您可以通过转义反斜杠本身来避免这种情况:

"Acb[".match('[\(, \), \[, \\]]')

-- -

It also seems that you're using commas to separate the characters in your character class - this is unnecessary, no separator is required. 似乎您在使用逗号分隔字符类中的字符-这是不必要的,不需要分隔符。 A simpler expression would thus be: 因此,一个简单的表达式是:

"Acb[".match(/[()[\]]/)

or 要么

"Acb[".match('[()[\\]]')

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

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