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

时间:2012-07-15 04:19:48

标签: javascript regex

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

我需要使用^ and $通过正则表达式匹配文本,以匹配从该字符串开始和结束的元素。但是,我需要能够使用变量:

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

所以我想匹配包含完全(从头到尾)我的变量name的每个字符串,但我不想匹配包含某个地方的变量name的字符串。

我该怎么做?

由于

3 个答案:

答案 0 :(得分:4)

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

i用于忽略大小写。 这只匹配单词“something”并且与somethingelse不匹配。

如果您希望在句子中间匹配它,则应在代码中使用以下内容

var name = ' something ';

Alernately,使用单词边界,

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

<强> Working Example

答案 1 :(得分:3)

如果您说要在字符串的开头结尾处匹配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 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");

答案 2 :(得分:1)

您应该使用/\bsomething\b/\b是匹配单词边界。

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