Showing posts with label regular expression. Show all posts
Showing posts with label regular expression. Show all posts

Regular expression





Character classes
.any character except newline
\w \d \sword, digit, whitespace
\W \D \Snot word, digit, whitespace
[abc]any of a, b, or c
[^abc]not a, b, or c
[a-g]character between a & g
Anchors
^abc$start / end of the string
\bword boundary
Escaped characters
\. \* \\escaped special characters
\t \n \rtab, linefeed, carriage return
\u00A9unicode escaped ©
Groups & Lookaround
(abc)capture group
\1backreference to group #1
(?:abc)non-capturing group
(?=abc)positive lookahead
(?!abc)negative lookahead
Quantifiers & Alternation
a* a+ a?0 or more, 1 or more, 0 or 1
a{5} a{2,}exactly five, two or more
a{1,3}between one & three
a+? a{2,}?match as few as possible
ab|cdmatch ab or cd

Reference: http://www.regexpal.com/


我們可以使用預先定義的字元類別: 
.符合任一字元
\d等於 [0-9] 數字
\D等於 [^0-9] 非數字
\s等於 [ \t\n\x0B\f\r] 空白字元
\S等於 [^ \t\n\x0B\f\r] 非空白字元
\w等於 [a-zA-Z_0-9] 數字或是英文字
\W等於 [^a-zA-Z_0-9] 非數字與英文字


. 符合任一字元。例如有一字串abcdebcadxbc,使用.bc來比對的話,符合的子字串有abc、ebc、xbc三個;如果使用..cd,則符合的子字串只有bcd。

以上的例子來根據字元比對,您也可以使用「字元類」(Character class)來比較一組字元範圍,例如: 


[abc]a、b或c
[^abc]非a、b、c的其它字元
[a-zA-Z]a到z或A到Z(範圍)
[a-d[m-p]]a到d或m到p(聯集)
[a-z&&[def]]d、e或f(交集)
[a-z&&[^bc]]a到z,除了b與c之外(減集)
[a-z&&[^m-p]]a到z且沒有m到p(a-lq-z)(減集)










一次只指定一個字元不過癮,也可以用Greedy quantifiers來指定字元可能出現的次數: 

X?X出現一次或完全沒有
X*X出現零次或多次
X+X出現一次或多次
X{n}X出現n次
X{n,}X出現至少n次
X{n,m}X出現至少n次,但不超過m次










Reference:
http://www.codeproject.com/Articles/9099/The-Minute-Regex-Tutorial
http://regex.learncodethehardway.org/book/