正则表达式(上) && 正则表达式.test方法检验string2是否存在于string1

正则表达式(Regular expressions或 regex)在编程语言中用于匹配字符串的部分。若想在'The dog chased the cat'中找到单词“the”,可以使用正则表达式:/the/。

注意,正则表达式中不需要引号。JavaScript有多种使用正则表达式的方法,检查正则表达式的一种方法是使用.test()方法。

.test()方法接受正则表达式,将其应用于字符串(放在括号内的),找到则返回true,没有找到则返回false。看例子:

let myString = "Hello, World!";
let myRegex = /Hello/;
//let result =myString.test(myRegex); //正则表达式才有test方法!这里报错:TypeError: myString.test is not a function
let result=myRegex.test(myString);
console.log(result); //true

但是,test方法是严格区分大小写的,只能匹配一个模式,任何其他形式的Hello都不匹配,即/Hello/不会匹配hello、HELLO等形式的字符串,只会返回false。

通过标志i可以实现不区分大小写的效果。正则表达式有很多标志(flag),但这里只需要关注忽略大小写的标志——i标志。即在正则表达式后紧跟(不能有空格)小写字母i (一定要是小写字母,大写字母是无效的),这样test检验字符串时就不会区分大小写:

let myString = "freeCodeCamp";
let fccRegex = /freecodecamp/i; //i与正则表达式之间不能有空隙!否则会报错:SyntaxError: unknown: Missing semicolon. 
let result = fccRegex.test(myString);
console.log(result);//true

可以使用alternation或or运算符搜索多个文字模式:|。此运算符可以匹配前后的文本式样。例如,如果要匹配字符串yes或no,则需要的正则表达式是/yes|no/。

当然也可以匹配多个:/yes|no|maybe/。例子:

let petString = "James has a pet cat.";
let petRegex = /dog|cat|bird|fish/;  
let result = petRegex.test(petString);
console.log(result);//true (petString里有cat文本式样,故会返回true。)

 使用通配符句点(.)匹配任何内容

有时,我们不知道或不需要知道模式中的确切字符。这时就可以使用通配符‘ . ’。通配符也称为句点,可以像正则表达式中的任何其他字符一样使用它。例如,如果要匹配hug, huh, hut, 和 hum,正则表达式就可以写成 /hu./ 以匹配所有四个单词: 

//例一:
let humStr = "I'll hum a song";
let hugStr = "Bear hug";
let huRegex = /hu./;
huRegex.test(humStr); //true
huRegex.test(hugStr); //true

//例二:
let exampleStr = "Let's have fun with regular expressions!";
let unRegex = /.un/;  
let result = unRegex.test(exampleStr);
console.log(result); //true

。。。

 

posted @ 2022-09-16 17:40  枭二熊  阅读(142)  评论(0编辑  收藏  举报