例如,正则表达式
/.+\s/
匹配的是“以空格符结尾的字符串”,我们用它来匹配苹果公司创始人乔布斯在斯坦福大学演讲的名言“You time is limited, so don’t waste it living someone else’s life.”:
/.+\s/.exec("You time is limited, so don’t waste it living someone else’s life.")[0] // 'You time is limited, so don’t waste it living someone else’s '
May God bless and keep you always, may your wishes all come true, may you always do for others and let others do for you. may you build a ladder to the stars and climb on every rung, may you stay forever young, forever young, forever young, May you stay forever young.
如何匹配以forever开头的那句歌词forever young, forever young呢?
这样写
/^forever.+/
是错误的:
/^forever.+/.exec("May God bless and keep you always,\nmay your wishes all come true,\nmay you always do for others\nand let others do for you.\nmay you build a ladder to the stars\nand climb on every rung,\nmay you stay forever young,\nforever young, forever young,\nMay you stay forever young.") // null
为什么错了?因为
^
匹配的整个字符串的开始,而是不是每一行的开始。
正则表达式指定
m
选项,即可支持多行匹配,这时
^
和
$
匹配的是每一行的开始和结束,因此正确的正则表达式是
/^forever.+/m
: