Match whole string

2018-12-30 23:57发布

What is the regular expression (in JavaScript if it matters) to only match if the text is an exact match? That is, there should be no extra characters at other end of the string.

For example, if I'm trying to match for abc, then 1abc1, 1abc, and abc1 would not match.

3条回答
与君花间醉酒
2楼-- · 2018-12-31 00:42

"^" For the begining of the line "$" for the end of it. Eg.:

var re = /^abc$/;

Would match "abc" but not "1abc" or "abc1". You can learn more at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

查看更多
听够珍惜
3楼-- · 2018-12-31 00:43

Use the start and end delimiters: ^abc$

查看更多
无色无味的生活
4楼-- · 2018-12-31 00:49

It depends. You could

string.match(/^abc$/)

But that would not match the following string: 'the first 3 letters of the alphabet are abc. not abc123'

I think you want to use \b (word boundaries)

var str = 'the first 3 letters of the alphabet are abc. not abc123';
var pat = /\b(abc)\b/g;
console.log(str.match(pat));

Live example: http://jsfiddle.net/uu5VJ/

If the former solution works for you, I would advise against using it.

That means you may have something like the following:

var strs = ['abc', 'abc1', 'abc2']
for (var i = 0; i < strs.length; i++) {
    if (strs[i] == 'abc') {
        //do something 
    }
    else {
        //do something else
    }
}

While you could use

if (str[i].match(/^abc$/g)) {
    //do something 
}

It would be considerably more resource intensive. For me, a general rule of thumb is for a simple string comparison use a conditional expression, for a more dynamic pattern use a regular expression.

more on JavaScript regex's: https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions

查看更多
登录 后发表回答