检验匹配 .test()
方法
语法
RegExpObject.test(string)
匹配返回true,不匹配返回false。
匹配不同可能性的文字字符串 |
使用 alternation
或 OR
运算符:|
。
如果你想匹配 yes
或 no
,你需要的正则表达式是 /yes|no/
。
你也可以搜索超过两种模式, /yes|no|maybe/
在匹配时忽略大小写 i
i:表示不区分大小写(case-insensitive)模式,即在确定匹配项时忽略模式与字符串的大小写
添加i标志到正则表达式,/ignorecase/i
。
该正则表达式可以匹配 ignorecase
,igNoreCase
和 IgnoreCase
。
提取匹配 .match()
方法
语法
"Hello, World!".match(/Hello/);
// 返回 ["Hello"]
var ourStr = "Regular expressions";
var ourRegex = /expressions/;
ourStr.match(ourRegex);
// 返回 ["expressions"]
查找多个匹配 g
多次搜索或提取,使用g标志。
可以在正则表达式上有多个标志,如/search/gi
g:表示全局(global)模式,即模式将被应用于所有字符串,而非在发现第一个匹配项时立即停止
var testStr = "Repeat, Repeat, Repeat";
var ourRegex = /Repeat/;
testStr.match(ourRegex);
// 返回 ["Repeat"]
var repeatRegex = /Repeat/g;
testStr.match(repeatRegex);
//返回["Repeat","Repeat","Repeat"]
使用通配符句号 .
匹配
通配符将匹配任意字符。通配符也可称为dot和period。
例如,想匹配hug
,huh
,hut
和hum
,可以使用正则表达式 /hu./
来匹配这所有四个字。
var humStr = "I'll hum a song";
var hugStr = "Bear hug";
var huRegex = /hu./;
humStr.match(huRegex); //返回["hum"]
hugStr.