regular expression rules 正则表达式
正则表达式是用于匹配字符串中字符组合的模式。在 JavaScript中,正则表达式也是对象。这些模式被用于 RegExp
的 exec
和 test
方法, 以及 String
的 match
、replace
、search
和 split
方法。本章介绍 JavaScript正则表达式。
创建一个正则表达式
1、使用一个正则表达式字面量,其由包含在斜杠之间的模式组成,如下所示:
1
2
3
4
5
6
7
|
<code class = " language-js" ><span class = "token comment" > /* /pattern/flags */ <span class = "token keyword" >const regex <span class = "token operator" >= <span class = "token regex" >/ab+c/<span class = "token punctuation" >; <span class = "token keyword" >const regex <span class = "token operator" >= <span class = "token regex" >/^[a-zA-Z]+[0-9]*W?_$/gi<span class = "token punctuation" >;</span></span></span></span></span></span></span></span></span></code>在加载脚本后,正则表达式字面值提供正则表达式的编译。当正则表达式保持不变时,使用此方法可获得更好的性能。<br><br>2、调用<code><a title= "zh-CN/docs/JavaScript/Reference/Global Objects/RegExp" href= "https://developer.mozilla.org/zh-CN/docs/JavaScript/Reference/Global_Objects/RegExp" >RegExp</a></code>对象的构造函数 |
1
2
3
4
5
6
7
8
9
|
<code class = " language-js" ><span class = "token comment" > /* new RegExp(pattern [, flags]) */ <span class = "token keyword" > let regex <span class = "token operator" >= <span class = "token keyword" > new <span class = "token class-name" >RegExp<span class = "token punctuation" >(<span class = "token string" > "ab+c" <span class = "token punctuation" >)<span class = "token punctuation" >; <span class = "token keyword" > let regex <span class = "token operator" >= <span class = "token keyword" > new <span class = "token class-name" >RegExp<span class = "token punctuation" >(<span class = "token regex" >/^[a-zA-Z]+[0-9]*W?_$/<span class = "token punctuation" >, <span class = "token string" > "gi" <span class = "token punctuation" >)<span class = "token punctuation" >; <span class = "token keyword" > let regex <span class = "token operator" >= <span class = "token keyword" > new <span class = "token class-name" >RegExp<span class = "token punctuation" >(<span class = "token string" > "^[a-zA-Z]+[0-9]*\W?_$" <span class = "token punctuation" >, <span class = "token string" > "gi" <span class = "token punctuation" >)<span class = "token punctuation" >;<br><br></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></code> |