\w
来匹配字母和数字[A-Za-z0-9_]
。不过,有可能想要搜寻的匹配模式是非字母数字字符。
可以使用\W
搜寻和\w
相反的匹配模式。注意,相反匹配模式使用大写字母。此缩写与[^A-Za-z0-9_]
是一样的。
```js
let shortHand = /\W/;
let numbers = "42%";
let sentence = "Coding!";
numbers.match(shortHand); // Returns ["%"]
sentence.match(shortHand); // Returns ["!"]
```
\W
来计算不同引号和字符串中非字母数字字符的数量。
'The five boxing wizards jump quickly.'
中匹配到 6 个非字母数字字符。"
testString: assert("The five boxing wizards jump quickly.".match(nonAlphabetRegex).length == 6);
- text: 正则表达式应该使用元字符来匹配非字母字符。
testString: assert(/\\W/.test(nonAlphabetRegex.source));
- text: "你的正则表达式应该在'Pack my box with five dozen liquor jugs.'
中匹配到 8 个非字母数字字符。"
testString: assert("Pack my box with five dozen liquor jugs.".match(nonAlphabetRegex).length == 8);
- text: "你的正则表达式应该在'How vexingly quick daft zebras jump!'
中匹配到 6 个非字母数字字符。"
testString: assert("How vexingly quick daft zebras jump!".match(nonAlphabetRegex).length == 6);
- text: "你的正则表达式应该在'123 456 7890 ABC def GHI jkl MNO pqr STU vwx YZ.'
中匹配到 12 个非字母数字字符。"
testString: assert("123 456 7890 ABC def GHI jkl MNO pqr STU vwx YZ.".match(nonAlphabetRegex).length == 12);
```