正则表达式-javascript

205 阅读1分钟

使用方法

1.text()

let myString = "Hello, World!";
let myRegex = /Hello/;
myString.test(myRegex); 

使用 | 匹配多个字符

let petString = "James has a pet cat.";
let petRegex = /dog|cat|bird|fish/;
let result = petRegex.test(petString)

2.match()

let extractStr = "Extract the word 'coding' from this string.";
let codingRegex = /coding/; 
let result = extractStr.match(codingRegex)
let twinkleStar = "Twinkle, twinkle, little star";
let starRegex = /Twinkle/gi;
let result = twinkleStar.match(starRegex)

在正则表达式后添加g表示全匹配,i表示忽略大小写。

正则表达式符号

. 匹配任何一个字符

let exampleStr = "Let's have fun with regular expressions!";
let unRegex = /.un/; // Change this line
let result = unRegex.test(exampleStr);

[] 匹配其中的某一字符

let quoteSample = "Beware of bugs in the above code; I have only proved it correct, not tried it.";
let vowelRegex = /[aeiou]/gi;
let result = qutoeSample.match(vowelRegex);
let quoteSample = "The quick brown fox jumps over the lazy dog.";
let alphabetRegex = /[a-e]/gi; 
let result = quoteSample.match(alphabetRegex); 

^ 取反 不匹配后面的字符

let quoteSample = "3 blind mice.";
let myRegex = /[^aeiou^0-9]/gi;
let result = quoteSample.match(myRegex);

使用^匹配开头

let firstString = "Ricky is first and can be found.";
let firstRegex = /^Ricky/;
firstRegex.test(firstString); True
let notFirst = "You can't find Ricky now.";
firstRegex.test(notFirst); False

使用$匹配结尾

let theEnding = "This is a never ending story";
let storyRegex = /story$/;
storyRegex.test(theEnding); True
let noEnding = "Sometimes a story will have to end";
storyRegex.test(noEnding);  False

+ 匹配 一次或多次的字符

let difficultSpelling = "Mississippi";
let myRegex = /s+/gi;
let result = difficultSpelling.match(myRegex);

* 匹配零次或多次字符

let chewieQuote = "Aaaaaaaaaaaaaaaarrrgh!";
let chewieRegex = /Aa*/; 
let result = chewieQuote.match(chewieRegex);

\w 相当于匹配 \A-Za-z0-9_
\d 相对于匹配 \0-9
\D 相反,匹配非数字 \s 匹配空格 {} 匹配 一定数量范围内的字符

let ohStr = "Ohhh no";
let ohRegex = /Oh{3,6} no/; 
let result = ohRegex.test(ohStr);

超前匹配(待补)