JS正则表达式完全匹配字符
js中 RegExp 对象使⽤ test() 来匹配正则表达式时,只要有⼦字符串能够匹配成功就会返回 true。
如果要当正则表达式完全匹配整个字符串时 test() 才返回true的话,可以在正则表达式的开头加⼊^ (表⽰开头),结尾加⼊$(表⽰结尾)。
var reg1 = /12345678/;
var reg2 = /^12345678$/;
var test1 = "12345678";
var test2 = "0123456789";
console.st(test1)); //true
console.st(test2)); //true
console.st(test1)); //true
console.st(test2)); //false
若想完整匹配⼀个单词,可以使⽤以下形式:
var reg2 = /\bword\b/;
var reg3 = /(?:^|(\s))word(?:$|\s)/;
其中 reg2 的正则表达式会匹配以 "-" 、"." 和其他的字符(没有⼀⼀去测)分隔的单词
⽽ reg3 的正则表达式只会匹配以空⽩字符分隔的单词
var testStr4 = "word";
var testStr5 = "wordwithoutspace";
var testStr6 = "a word with space";
var testStr7 = "a-word-with-strikethrough";
var testStr8 = "a0word0with0number";
var testStr9 = "a_word_with_underline";
var testStr10 = "a.word.with.decimal";
var testStr11 = "a word with tab";
var reg2 = /\bword\b/;
console.log("st(testStr4)",st(testStr4)); //true
console.log("st(testStr5)",st(testStr5)); //false
console.log("st(testStr6)",st(testStr6)); //true
console.log("st(testStr7)",st(testStr7)); //truejs中文正则表达式
console.log("st(testStr8)",st(testStr8)); //false
console.log("st(testStr9)",st(testStr9)); //false
console.log("st(testStr10)",st(testStr10)); //true
console.log("st(testStr11)",st(testStr11)); //true
console.log()
var reg3 = /(?:^|(\s))word(?:$|\s)/;
console.log("st(testStr4)",st(testStr4)); //true
console.log("st(testStr5)",st(testStr5)); //false
console.log("st(testStr6)",st(testStr6)); //true
console.log("st(testStr7)",st(testStr7)); //false
console.log("st(testStr8)",st(testStr8)); //false
console.log("st(testStr9)",st(testStr9)); //false
console.log("st(testStr10)",st(testStr10)); //false
console.log("st(testStr11)",st(testStr11)); //true
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论