使用正则表达式中的变量与$和^匹配字符串

Matching string using variable in regular expression with $ and ^

本文关键字:字符串 正则表达式 变量      更新时间:2023-09-26

这可能是一个很容易回答的问题,但我还没有弄清楚什么是正确的方法。

我需要使用^ and $通过正则表达式匹配文本,以便只匹配以该字符串开头和结尾的元素。然而,我需要能够使用一个变量来做到这一点:

var name // some variable
var re = new RegExp(name,"g");

因此,我想匹配(从开始到结束)完全包括我的变量name的每个字符串,但我不想匹配在某个地方包含我的变量name的字符串。

我该怎么做?

感谢

var strtomatch = "something";
var name = '^something$';
var re = new RegExp(name,"gi");
document.write(strtomatch.match(re));

i用于忽略大小写。这只和单词"something"匹配,不会和somethingsese匹配。

如果你想在句子中间匹配它,你应该在你的代码中使用以下内容

var name = ' something ';

提醒,使用单词边界,

var name = '''bsomething''b';

工作示例

如果您想在字符串的开头结尾匹配something,请执行以下操作:

/^something|something$/

使用您的变量:

new RegExp("^" + name + "|" + name + "$");

编辑:对于您更新的问题,您希望name变量是匹配的整个字符串,因此:

new RegExp("^" + name + "$"); // note: the "g" flag from your question
                              // is not needed if matching the whole string

但除非name本身包含正则表达式,否则这是毫无意义的,因为尽管你可以说:

var strToTest = "something",
    name = "something",
    re = new RegExp("^" + name + "$");
if (re.test(strToTest)) {
   // do something
}

你也可以说:

if (strToTest === name) {
   // do something
}

编辑2:好吧,从您的评论中,您似乎在说正则表达式应该与测试字符串中任何地方出现的"something"作为离散词相匹配,所以:

"something else"           // should match
"somethingelse"            // should not match
"This is something else"   // should match
"This is notsomethingelse" // should not match
"This is something"        // should match
"This is something."       // should match?

如果这是正确的,那么:

re = new RegExp("''b" + name + "''b");

您应该使用/'bsomething'b/。CCD_ 9是为了匹配单词边界。

"A sentence using something".match(/'bsomething'b/g);