javascript - I can't figure out a regular expression, please help me
天蓬老师
天蓬老师 2017-05-19 10:31:59
0
2
426

Code:

var match1 = new RegExp('\S*//weibo\.com/p/\S*');
var match2 = new RegExp('\S*//weibo\.com/p/\S+');

match1.test('http://weibo.com/p/12345/myfollow?relate=fans#place');//true
match2.test('http://weibo.com/p/12345/myfollow?relate=fans#place');//false

I’m a little confused, why match2 is false, and what the hell does match1 match?

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(2)
阿神

Brother, there is something wrong with your regular expression. First of all, there are two forms of regular expression construction, one is like yours, and the other is /abc/g.

Depending on what you mean, your regular expression should be written like this:

var match1 = new RegExp('\S*//weibo\.com/p/\S*');
var match2 = new RegExp('\S*//weibo\.com/p/\S+');

Yours is missing a backslash and the escaping fails

Why? Because according to your regular expression, actually:

var match1 = new RegExp('\S*//weibo\.com/p/\S*');
match1.source;
// "S*\/\/weibo.com\/p\/S*"

Then there is the difference of *+, so the first one is true and the second one is false.

It is recommended to use two slashes when constructing a regular expression, so that there is no need to escape:

var match1 = /\S*\/\/weibo\.com\/p\/\S/;
match1.source;
// "\S*\/\/weibo\.com\/p\/\S"
黄舟

match1: s matches 0 to 1 or more spaces. //It is best to escape this and use // so that the matched one is '/'. This matches '.', if there is no backslash The bar matches any character, and the last s matches 0 to 1 or more spaces.
match2: Only the last one is different, s+, one or more spaces, but your string obviously has no spaces after p, so it is false

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template