2017年11月08日09:57:27再次重新系统的开始学习正则表达式,希望这次可以真正的学会!
语法学习
1. Character classes
Character classes match a character from a specific set. There are a number of predefined(预定的) character classes and you can also define your own sets.
用法 | 匹配 |
---|---|
. |
匹配任何字符,除了换行符(any character except newline) |
\w ,\d ,\s |
字符,数字,空白(word,digit,whitespace) |
\W ,\D ,\S |
非字符,非数字,非空白( not word,whitespace) |
[abc] |
any of a,b,or c 【中间没有任何字符分隔】 |
[^abc] |
not a,b or c (出了个a,c其余的) |
[a-g] |
character between a & g |
\b |
匹配单词(word)边界位置,如空格,标点符号或字符串的开始/结尾。这匹配一个位置,而不是一个字符。(Matches a word boundary position such as whitespace,punctuation,or the start/end of the string. This matches a position,not a character.) |
\B |
匹配不是单词边界的任意位置,这匹配的是一个位置,不是一个字符。 |
\w |
匹配任何单词字符(字母数字和下划线)。只匹配low-ascii字符(没有重音或非罗马字符)。相当于[A-Za-z0-9_](Matches any word character (alphanumeric & underscore). Only matches low-ascii characters (no accented or non-roman characters). Equivalent to [A-Za-z0-9_]) |
\W |
Matches any character that is not a word character (alphanumeric & underscore). Equivalent to [^A-Za-z0-9_] |
\d |
Matches any digit character (0-9). Equivalent to [0-9]. |
\D |
Matches any character that is not a digit character (0-9). Equivalent to [^0-9]. |
\s |
Matches any whitespace character (spaces,tabs,line breaks(换行符)). |
\S |
Matches any character that is not a whitespace character (spaces,line breaks). |
character set(字符集)[aeIoU] |
Match any character in the set. |
negated set(非字符集)[^aeIoU] |
Match any character that is not in the set. |
range: [a-z] |
Matches a character having a character code between the two specified characters inclusive.(在两个指定的字符之间匹配具有字符代码的字符) |
2. Anchors (锚)
Anchors are unique in that they match a position within a string,not a character.
是独一无二的,它们匹配的位置在一个字符串,而不是一个字符。
用法 | 匹配 |
---|---|
begining : ^ |
Matches the beginning of the string,or the beginning of a line if the multiline flag (m) is enabled. This matches a position,not a character. e.g.: /^\w+/gm – He is a boy. |
end: $ |
Matches the end of the string,or the end of a line if the multiline flag (m) is enabled. This matches a position,not a character. e.g.:/\w+$/g – I am a girl_ |
word boundary(边界)\b |
Matches a word boundary position such as whitespace(空白),punctuation(标点符号),or the start/end of the string. This matches a position,not a character. e.g.:/m\b/gm – me e**m** ;/\bm/gm – **m**e em ; |
not word boundary \B |
Matches any position that is not a word boundary. This matches a position,not a character. e.g.:/\w\B/gm –I **a**m a **girl**_ **m**e **e**m |
3. Escapaed characters(转义字符)
Some characters have special meaning in regular expressions and must be escaped(避免). All escaped characters begin with the \ character.
Within a character set,only,-,and ] need to be escaped.
用法 | 匹配 |
---|---|
octal escape:\251 |
Octal(八进制) escaped character in the form \000. Value must be less than 255 (\377).(八进制需要转义的字符是从\000 到\377 (十进制的255))e.g.: /\255/g – RegExr is ©2017.(其中©是被匹配的) |
Hexadecimal(16进制) escape:\xA9 |
Hexadecimal escaped character in the form \xFF. e.g.: /\xA9/g – RegExr is ©2017.(其中©是被匹配的) |
Unicode escape:\u00A9 |
Unicode escaped character in the form \uFFFF. e.g.: /\u00A9/g – RegExr is ©2017.(其中©是被匹配的) |
control character escape | Escaped control character in the form \cZ. This can range from \cA (NULL,char code 0) to \cZ (EM,char code 25). e.g.: \cI matches TAB (char code 9). |
tab: \t |
Matches a TAB character (char code 9). |
line Feed : \n |
Matches a LINE Feed character (char code 10 - 换行键). |
vertical tab: \v |
Matches a VERTICAL TAB character (char code 11 - 垂直制表符). |
form Feed:\f |
Matches a FORM Feed character (char code 12-换行键). |
carriage return :\r |
Matches a CARRIAGE RETURN character (char code 13 - 回车键). |
null : \0 |
Matches a NULL character (char code 0 - 空字符). |
点.: \. |
Matches a “.” character (char code 46). |
斜杠 \ : \\ |
Matches a “\” character (char code 92). |
\+
|
Matches a “+” character (char code 43). |
\*
|
Matches a “*” character (char code 42). |
?:\? |
Matches a “?” character (char code 63). |
^: \^ |
Matches a “^” character (char code 94). |
[: \[
| Matches a “[” character (char code 91).
]: \]
| Matches a “]” character (char code 93).
{:\{
| Matches a “{” character (char code 123).
}: \}
| Matches a “}” character (char code 125).
(: \(
| Matches a “(” character (char code 40).
): \)
| Matches a “)” character (char code 41).
|: \|
| Matches a “|” character (char code 124).
/: \/
| Matches a “\/” character (char code 47).
4. Groups & Lookaround(组和查看)
组允许您将一系列令牌组合在一起操作。捕获组可以通过反向引用来引用,并在结果中单独访问。
(Groups allow you to combine a sequence of tokens to operate on them together. Capture groups can be referenced by a backreference and accessed separately in the results.)
Lookaround让你匹配一个组,而不会在结果中包含它。
(Lookaround lets you match a group without including it in the result.)
用法 | 匹配 |
---|---|
capturing group(捕获组): (ABC) |
将多个标记组合在一起,并创建一个提取子字符串或使用反向引用的捕获组。(Groups multiple tokens together and creates a capture group for extracting a substring or using a backreference.) (备注1) |
backreference(对捕获组的反向引用): \1 ,\3 ,\num |
Matches the results of a prevIoUs capture group. For example \1 matches the results of the first capture group & \3 matches the third. 对前面捕获分组的引用。 e.g. : var str = 'abccab abc aba cbc dbd;' 结果:str.match(/(\w)b\1/g) -> (3) ["aba","cbc","dbd"] (\num代表捕获到的第一个值) |
non-capturing group:(?:ABC) |
Groups multiple tokens together without creating a capture group. (没有搞明白) |
以下是断言 | – |
positive lookahead: (?=ABC) |
Matches a group after the main expression without including it in the result. 向指定xxx后边肯定会出现ABC,就用正先行断言,表达式:(?=ABC) e.g.: \d(?=px) – 1pt **2**px 3em **4**px |
nagative lookahead: (?!ABC) |
Specifies a group that can not match after the main expression (if it matches,the result is discarded). 向指定xxx后边肯定不会出现ABC,就用正先行断言,表达式:(?!ABC) e.g.: \d(?=px) – **1**pt 2px **3**em 4px |
备注1 - 捕获组:
捕获组就是把正则表达式中子表达式匹配的内容,保存到内存中以数字编号或显式命名的组里,方便后面引用。当然,这种引用既可以是在正则表达式内部,也可以是在正则表达式外部。
备注2 - 断言:
所谓断言,就是指明某个字符串前边或者后边,将会出现满足某种规律的字符串。
5. Quantifiers & Alternation
量词指示前面的标记必须匹配一定的次数。在默认情况下,量词是贪婪的,并且会匹配尽可能多的字符。
交替行为像一个布尔OR,匹配一个或另一个序列。(Alternation acts like a boolean OR,matching one sequence or another.)
用法 | 匹配 |
---|---|
plus: + |
Matches 1 or more of the preceding token. |
star: * |
Matches 0 or more of the preceding token. |
quantifier: {1,3} |
Matches the specified quantity of the prevIoUs token. {1,3} will match 1 to 3. {3} will match exactly 3. {3,} will match 3 or more. |
optional: ? |
Matches 0 or 1 of the preceding token(上述标记),effectively making it optional.(使其成为可选项) eg. : /colou?r/g – color colour |
lazy: ? |
Makes the preceding(前) quantifier(量词) lazy,causing it to match as few characters as possible. By default,quantifiers are greedy(贪婪的),and will match as many characters as possible. eg. : b\w+? – b be **be**e **be**er **be**ers |
alternation:| |
Acts like a boolean OR. Matches the expression before or after the | .It can operate within a group,or on a whole expression. The patterns will be tested in order.(它可以在一个小组内或者是整个表达内内运行,模式将按顺序进行测试) eg. :b(a|e|i)d – bad bud bod bed bid |
6. Substitution (代替)
These tokens are used in a substitution string to insert different parts of the match.(这些令牌用于替换字符串插入的不同部分匹配。)
用法 | 匹配 |
---|---|
match:$& |
Inserts the matched text. eg. 题目:'意见-rightClick-modal'.replace(/([^-]*)-/,'===$&====') 结果:"===意见-====rightClick-modal" |
capture group: $1 |
Inserts the results of the specified capture group. For example,$3 would insert the third capture group. 详细解释在下:1.2 捕获组编号规则 |
before match: $` | Inserts the portion of the source string that precedes the match.(插入匹配之前的源字符串部分) |
after match : $’ | Inserts the portion of the source string that follows the match. |
escaped: $ |
Inserts a dollar sign character ($). e.g.. > test = 'abcdefg'; > test.replace(/ab(\w+?)[\D\d]*e(\w+?).*/g,'$2$') < "f$" |
7. Flags
用法 | 匹配 |
---|---|
ignore case : i |
Makes the whole expression case-insensitive(不区分大小写). For example,/aBc/i would match AbC. |
global search: g |
Retain the index of the last match,allowing subsequent(后续的) searches to start from the end of the prevIoUs match. |
multiline: m |
When the multiline flag is enabled,beginning and end anchors (^ and
|
Unicode:u |
When the unicode flag is enabled,you can use extended(扩展) unicode escapes in the form \x{FFFFF}.It also makes other escapes stricter,causing unrecognized escapes (ex. \j) to throw an error. |
sticky:y |
It also makes other escapes stricter,causing unrecognized escapes (ex. \j) to throw an error.(该表达式只能匹配lastIndex的位置,如果设置则忽略全局(g)标志。 由于RegExr中的每个搜索都是离散的,因此此标志对显示的结果没有进一步的影响。) |
重点详解
1. 捕获组
1.1 what
捕获组就是把正则表达式中子表达式匹配的内容,保存到内存中以数字编号或显式命名的组里,方便后面引用。当然,这种引用既可以是在正则表达式内部,也可以是在正则表达式外部。
捕获组有两种形式,一种是普通捕获组,另一种是命名捕获组,通常所说的捕获组指的是普通捕获组。语法如下:
普通捕获组:(Expression)
命名捕获组:(?Expression)
普通捕获组在大多数支持正则表达式的语言或工具中都是支持的,而命名捕获组目前只有.NET、PHP、Python等部分语言支持,据说Java会在7.0中提供对这一特性的支持。上面给出的命名捕获组的语法是.NET中的语法,另外在.NET中使(?’name’Expression)
与使用(?<name>Expression)
等价的。在PHP和Python中命名捕获组语法为:(?P<name>Expression)
。
另外需要说明的一点是,除(Expression)
和(?<name>Expression)
语法外,其它的(?...)
语法都不是捕获组。
1.2 捕获组编号规则:$1\$2\$3...$n
编号规则指的是以数字为捕获组进行编号的规则,在普通捕获组或命名捕获组单独出现的正则表达式中,编号规则比较清晰,在普通捕获组与命名捕获组混合出现的正则表达式中,捕获组的编号规则稍显复杂。
在展开讨论之前,需要说明的是,编号为0的捕获组,指的是正则表达式整体,这一规则在支持捕获组的语言中,基本上都是适用的。下面对其它编号规则逐一展开讨论。
通俗的解释:
1, 2…是表示的小括号里的内容 ,1是第一个小括号里的, 2是第2个小括号里的
e.g.var test = ‘abcde acerfade sdfjawide hello dfwaf’;
test.replace(/a(\w+?)[\D\d]he(\w+?)[\D\D]/g,‘1− 2’)
结果: “b-l”
第一个分组匹配出来的是“b”,第二个分组匹配出来的是”l”,所以将$1-$2
的结果就是b-l
。
而[\D\d]是匹配任意字符
1.2.1普通捕获组
如果没有显式为捕获组命名,即没有使用命名捕获组,那么需要按数字顺序来访问所有捕获组。在只有普通捕获组的情况下,捕获组的编号是按照“(”出现的顺序,从左到右,从1开始进行编号的。
e.g.:正则表达式:(\d{4})-(\d{2}-(\d\d))
上面的正则表达式可以用来匹配格式为yyyy-MM-dd的日期,为了在下表中得以区分,月和日分别采用了\d{2}和\d\d这两种写法。
用以上正则表达式匹配字符串:2008-12-31,匹配结果为:
编号 | 命名 | 捕获组 | 匹配内容 |
---|---|---|---|
0 | (\d{4})-(\d{2}-(\d\d)) | 2008-12-31 | |
1 | (\d{4}) | 2008 | |
2 | (\d{2}-(\d\d)) | 12-31 | |
3 | (\d\d) | 31 |
e.g.: 浏览器中执行的结果:
> var dateStr = '2008-12-31';
> datestr.match(/(\d{4})-(\d{2}-(\d\d))/g);
< ["2008-12-31"]
> datestr.match(/(\d{4})-(\d{2}-(\d\d))/)
< (@H_283_1301@4) ["2008-12-31","2008","12-31","31",index: @H_283_1301@0,input: "2008-12-31"]
为什么会有这两种不同的结果呢?
这是JavaScript中
match()
方法的特性。match方法的返回值存放匹配结果的数组。该数组的内容依赖于 regexp 是否具有全局标志 g。
* 如果 regexp 没有标志 g,那么 match() 方法就只能在 stringObject 中执行一次匹配。如果没有找到任何匹配的文本, match() 将返回 null。否则,它将返回一个数组,其中存放了与它找到的匹配文本有关的信息。该数组的第 0 个元素存放的是匹配文本,而其余的元素存放的是与正则表达式的子表达式匹配的文本。除了这些常规的数组元素之外,返回的数组还含有两个对象属性。index 属性声明的是匹配文本的起始字符在 stringObject 中的位置,input 属性声明的是对 stringObject 的引用* 如果 regexp 具有标志 g,则 match() 方法将执行全局检索,找到 stringObject 中的所有匹配子字符串。若没有找到任何匹配的子串,则返回 null。如果找到了一个或多个匹配子串,则返回一个数组。不过全局匹配返回的数组的内容与前者大不相同,它的数组元素中存放的是 stringObject 中所有的匹配子串,而且也没有 index 属性或 input 属性。
注意:在全局检索模式下,match() 即不提供与子表达式匹配的文本的信息,也不声明每个匹配子串的位置。如果您需要这些全局检索的信息,可以使用 RegExp.exec()。
由于普通捕获组编号顺序从0开始,那么可以使用$1,$2,$..
来进行表示。e.g:
> datestr.replace(/(\d{@H_283_1301@4})-(\d{@H_283_1301@2}-(\d\d))/,"$1年$2号");
< "2008年12-31号"