文字匹配模式(/literal/
)和通配符(/./
),
是正则表达式的两种极端情况,一种是精确匹配,而另一种则是匹配所有。
在这两种极端情况之间有一个平衡选项。
我们可以使用字符集
搜寻指定的文字匹配模式。
我们可以把字符集放在方括号([
和]
)之间来定义一组需要匹配的字符串。
例如,如果想要匹配"bag"
、"big"
和"bug"
,但是不想匹配"bog"
。
可以创建正则表达式/b[aiu]g/
来执行此操作。
[aiu]
是只匹配字符"a"
、"i"
或者"u"
的字符集。
var bigStr = "big";
var bagStr = "bag";
var bugStr = "bug";
var bogStr = "bog";
var bgRegex = /b[aiu]g/;
console.log( bigStr.match(bgRegex) ); // 返回 ["big"]
console.log( bagStr.match(bgRegex) ); // 返回 ["bag"]
console.log( bugStr.match(bgRegex) ); // 返回 ["bug"]
console.log( bogStr.match(bgRegex) ); // 返回 null
闯关:使用元音字符集(a
、e
、i
、o
、u
)在正则表达式vowelRegex
中匹配到字符串quoteSample
中的所有元音。
注意一定要同时匹配大小写元音。
var quoteSample = "When you were born,you were crying and everyone around you was smiling.";
var vowelRegex = /change/; // 修改这行
var result = vowelRegex; // 修改这行
console.log(result);
正确代码
var quoteSample = "When you were born,you were crying and everyone around you was smiling.";
var vowelRegex = /[aeiou]/ig;
var result = quoteSample.match(vowelRegex);