为什么这两个正则表达式的行为不一样? [英] Why do these 2 regular expressions not behave the same?
问题描述
我正在尝试使用构造函数语法创建一个正则表达式,例如 new RegExp('\ bword \b','g')
,但它确实如此不按预期行事。相反,它似乎创建了一个正则表达式,看起来像 / \\\ bwor \b / g
,并且缺少最后一个字母。
I am attempting to create a regular expression with the constructor syntax like this new RegExp('\bword\b', 'g')
, but it does not behave as expected. Rather it seems to create a regular expression that looks like this /\bwor\b/g
with a missing last letter.
我必须使用构造函数语法来创建正则表达式,因为我是从json文件动态创建的,并且你不能将正则表达式放在json中。所以我的问题是:
I have to use the constructor syntax to create the regular expression as I am dynamically creating the from a json file, and you can't put regex in json. So my question's are:
a。为什么这些表现不一样?和b。我可以做些什么来弥补这种情况?
a. Why do these behave differently? and b. What can I do to remedy the situation?
注意:我试图做的是创建一个只与整个单词匹配的正则表达式而不是一个单词另一个词。
Note: What I am attempting to do is create a regular expression that matches a whole word only and not a word that exists within another word.
推荐答案
对于字符串 \ b
表示退格。
对于正则表达式 \ b
表示字边界。
要确保使用正则表达式版本,请在每个反斜杠之前添加一个额外的反斜杠 \
用于转义转义字符的字符串。
To make sure the regex version is used, add an extra backslash \
before each backslash in the string to escape the escape characters.
这篇关于为什么这两个正则表达式的行为不一样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!