Introducing Regular Expressions 读书笔记
工具:
regexbuddy:http://download.csdn.net/tag/regexbuddy%E7%A0%B4%E8%A7%A3
在线测试平台:
进阶读物:
资料:
Notepad++ Regex: http://sourceforge.net/apps/mediawiki/notepad-plus/index.php?title=Regular_Expressions
文中 “项 ” 表示 一个字符或者是一个字符组(group)的概念。
chapter 1:
[ ]:字符集匹配
d:匹配数字0-9,同 "[0-9]"
D:匹配非数字,包括字母、标点等
. :(dot)通配符,匹配所有字符(除换行符),但当出现在[ ]中时表示字符dot
向后引用 (Backreferences)
( ):成组,capturing group
1 或 $1:匹配与第一个括号的匹配项内容完全一样的项,不同的正则表达式的实现可能形式不一样,有的只支持1,有的只支持$1,有的都支持。
例:
(d)d1:匹配202,303,151,不能匹配234.
修饰符
{ }:大括号内为前一项的精确匹配次数,可为{3}(3次),{3,5}(3到5次,即3,4,5次都可以,注意逗号两边不能有空格)或{3,}(大于等于3次)这样的形式。
?:匹配前一项0或1次,尽可能多的匹配,贪心(greedy)
+:匹配前一项1次或多次(内容不必完全一样,只要都符合相同的匹配规则即可,如 "d+",表示匹配尽可能多的数字),尽可能多的匹配,贪心(greedy)
*:匹配前一项0次或多次(内容不必完全一样),尽可能多的匹配,贪心(greedy)
|:(the vertical bar) indicates alternation, that is, a given choice of alternatives,该符号前面的匹配式匹配失败后就使用后面的匹配式进行匹配
^:出现在开头或 | 之后时表示 行首
$:行尾
:转义字符,可以将上述修饰符转成普通字符,如字符左括号“(”
例:
d{3}-?d{3}-?d{4}
(d{3,4}[.-]?)+
(d{3}[.-]?){2}d{4}
^((d{3})|^d{3}[.-]?)?d{3}[.-]?d{4}$:匹配(201)971-1975,201-971-1975,(201)971.1975,201.971.1975。
chapter 2
^:match all but these,如[^0-9],表示匹配所有非数字
w:匹配字母和数字,与 [0-9a-zA-Z] 相同
W:与w相反,[^0-9a-zA-Z]
.*:匹配0个或多个任意字符
.+:匹配1个或多个任意字符
dotall mode:开启这个模式后 ‘.’ 将匹配包括换行在内的所有字符
下面是一个快捷字符表:
Table 2-1. Character shorthands
Character Shorthand | Description
a: Alert
:Word boundary,单词边界
[]: Backspace character
B: Non-word boundary,非单词边界
c :x Control character
d: Digit character
D :Non-digit character
d xxx: Decimal value for a character
f :Form feed character
: Carriage return
: Newline character,换行符
pass:[<literal>o</literal> :Octal value for a character
<replaceable>xxx</replaceable>]
s: Space character,空白符
S :Non-space character
:Horizontal tab character,tab符
v: Vertical tab character
w: Word character
W :Non-word character