当前位置:嗨网首页>书籍在线阅读

20-单词边界匹配

  
选择背景色: 黄橙 洋红 淡粉 水蓝 草绿 白色 选择字体: 宋体 黑体 微软雅黑 楷体 选择字体大小: 恢复默认

17.18 单词边界匹配

正则表达式中一个经常被忽视,但却非常有用的特性是单词边界匹配。类似开始锚点和行末锚点,单词边界匹配是\b,取反是\B,它不消费输入内容。这是一个非常好用的特性,马上就可以看到如何使用它。

单词边界界定为一个\w匹配之前或之后紧挨着一个\W(非单词)字符,或字符串的开始或结尾。假设试图将英文中的邮件地址替换成超链接(为了方便解释,假定邮件地址以一个字母开始和一个字母结束)。想想那些需要考虑到的不同情况:

const inputs = [
   "[email protected]",               // nothing but the email
   "[email protected] is my email",   // email at the beginning
   "my email is [email protected]",   // email at the end
   "use [email protected], my email", // email in the middle, with comma afterward
   "my email:[email protected].",     // email surrounded with punctuation
];

虽然有很多种不同的情况,但是所有这些邮件地址有一个共同点:它们都处在单词的边界。单词边界标记的另一个好处是,因为它们不消费输入,所以不用担心“将它们放回“到替换字符串中:

const emailMatcher =
   /\b[a-z][a-z0-9._-]*@[a-z][a-z0-9_-]+\.[a-z]+(?:\.[a-z]+)?\b/ig;
inputs.map(s => s.replace(emailMatcher, '<a href="mailto:$&">$&</a>'));
// returns [
//    "<a href="mailto:[email protected]">[email protected]</a>",
//    "<a href="mailto:[email protected]">[email protected]</a> is my email",
//    "my email is <a href="mailto:[email protected]">[email protected]</a>",
//    "use <a href="mailto:[email protected]">[email protected]</a>, my email",
//    "my email:<a href="mailto:[email protected]>[email protected]</a>.",
// ]

除了单词边界匹配,这个正则表达式还使用了本章中讲到的很多特性:初看时可能会让人望而生畏,但如果能花些时间将它们搞懂,则离成为正则表达式大师更近了(这里要注意特别替换宏,$&,它确实没有包含邮件地址周围的字符,因为那些字符没有被消费)。

当需要搜索以其他单词开始、结束或包含其他单词的文本时,使用单词边界也非常方便。例如, /\bcount/ 会找到count和countdown,但不会找到discount、recount或accountable。而 /\bcount\B/ 只能找到countdown,/\Bcount\b/会找到discount和recount,而 /\Bcount\B/ 只能找到accountable。