简体   繁体   English

这个正则表达式是什么:/ [\\ [] /?

[英]What does this regular expression: /[\[]/?

我很难理解这意味着什么: /[\\[]/为什么有两个替换语句?

name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");

/[\\[]/ is a regular expression literal . /[\\[]/是一个正则表达式文字

In the first replacement, you're replacing a [ by \\[ and the symetric in the second one. 在第一次替换中,您将替换[ by \\[和第二个中的symetric。

It looks weird because of many (mostly useless) escapements : [ is escaped in the regex and \\ and [ are escaped in the string literal. 由于许多(通常是无用的)擒纵机构,它看起来很奇怪: [在正则表达式中被转义而且\\[在字符串文字中被转义。

The first regex can be analyzed like this : 可以像这样分析第一个正则表达式:

  • / : regex opening / :正则表达式开放
  • [ : character set opening [ :字符集开放
  • \\[ : the [ character (with an escaping that is useless as it's in a set) \\[[字符(因为它在集合中没有用的转义)
  • ] : character set closing ] :字符集关闭
  • / : regex closing / :正则表达式结束

Those regexes look too verbose to me : you don't need a character set if you have just one character in that set. 那些正则表达式看起来太冗长了:如果你在该集合中只有一个字符,则不需要字符集。 And you don't need to escape the [ in the string literal. 而且你不需要逃避[在字符串文字中。

You could have done 你可以做到的

 name = name.replace(/\[/, "\\[").replace(/\]/, "\\]");

For example 例如

 'a [ b c ] d [ e ]'.replace(/\[/, "\\[").replace(/\]/, "\\]")

gives

 "a \[ b c \] d [ e ]"

Note that as there is no g modifier, you're only doing one replacement in each call to replace , which probably isn't the goal, so you might want 请注意,因为没有g修饰符,所以每次调用只需要替换一个replace ,这可能不是目标,所以你可能想要

 name = name.replace(/\[/g, "\\[").replace(/\]/g, "\\]");

That is using regular expression. 那是使用正则表达式。 If you are not familiar with regular expression, you may want to study that first. 如果您不熟悉正则表达式,您可能需要先学习它。

This really isn't specific to Javascript, regular expressions are used in most programming languages with slight variations. 这实际上并不特定于Javascript,正则表达式在大多数编程语言中使用,略有不同。 Look into regular expressions, very useful once you know it! 查看正则表达式,一旦你知道它就非常有用!

Maybe you will see how it works on example 也许你会在例子中看到它是如何工作的

var name = "[[[[[]]]]]]]";
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
console.log(name);

as result you will have 结果你会有

\[[[[[\]]]]]]] 

This regular expression replace first occurrence of [ to \\[ and first occurrence ] to \\] 这个正则表达式将[ to \\[和first occurrence ]第一次出现替换为\\]

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

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