標籤:style 使用 strong width io new
元字元
我們使用的字元“[”和“]”叫元字元,對模式有特殊的效果。這種元字元共有11個,它們扮演著不同的角色。如果想在建立的模式中包含這些元字元中的某一個字元,需要在該字元前使用逸出字元“\”。
元字元 |
描述 |
^ 開始 (beginning) |
字元“^”之後的實體(entity),必須在配匹配的字串開始部分找到。 例: ^h 能匹配的字串:hello,h,hh 不能匹配的字串:character,ssh |
$ 結束 (end) |
字元“$”之前的實體(entity),必須在配匹配的字串尾部找到。 例: e$ 能匹配的字串:sample,e,file 不能匹配的字串:extra,shell |
. 任何字元 (any) |
匹配任何字元。 例: hell. 能匹配的字串:hello,hellx,hell5,hell! 不能匹配的字串:hell,helo |
[] 組 (set) |
匹配指定字元集內的任何字元。 文法:[a-z]表示一個區間,[abcd]表示一組,[a-z0-9]表示兩個區間。 例: hell[a-y123] 能匹配的字串:hello,hell1,hell2 不能匹配的字串:hellz,hell4,heloo |
[^ ] 否定組 (negate set) |
匹配任何不包括在指定字元集內的字串 例: hell[^a-np-z0-9] 能匹配的字串:hello,hell 不能匹配的字串:hella,hell5 |
| 或 (alternation) |
匹配符號“|”之前或之後的實體。 例: hello|welcome 能匹配的字串:hello,welcome,helloes,awelcome 不能匹配的字串:hell,ellow,owelcom |
() 分組 (grouping) |
組成一組用於匹配的實體(entity),常用符號“|”協助完成。 例: ^(hello|hi)there$ 能匹配的字串:hello there,hi there 不能匹配的字串:hey there,ahoy there |
\ 轉義 (escape) |
允許你對一個特殊字元轉義(即將具有特殊意義的字元變為普通的文本字元) 例: hello\. 能匹配的字串:hello.,hello... 不能匹配的字串:hello,hella |
量詞
可以通過使用有限的字元來表達簡單的匹配。下表所示的量詞允許你擴充實體匹配使用量詞可以定製匹配的次數。
量詞 |
描述 |
* 0或多次 |
字元“*”之前的實體被發現0次或多次。 例: he*llo 能匹配的字串:hllo,hello,heeeello 不能匹配的字串:hallo,ello |
+ 1或多次 |
字元“+”之前的實體被發現1次或多次。 例: he+llo 能匹配的字串:hello,heeello 不能匹配的字串:hllo,helo |
? 0或1次 |
字元“?”之前的實體被發現0次或1次。 例: he?llo 能匹配的字串:hello,hllo 不能匹配的字串:heello,heeeello |
{x} x次 |
字元“{}”之前的字元必須匹配指定的x次數。 例: he{3}llo 能匹配的字串:heeello,oh heeello 不能匹配的字串:hello,heello,heeeello |
{x,} 至少x次 |
字元“{}”之前的字元必須至少出現x次。(即可以多於x次) 例: he{3}llo 能匹配的字串:heeello,heeeeello 不能匹配的字串:hllo,hello,heello |
{x,y} x到y次 |
字元“{}”之前的字元出現的次數必須介於x和y次之間。 例: he{2,4}llo 能匹配的字串:heello,heeello,heeeello 不能匹配的字串:hello,heeeeello |
捕獲
Regex機制最後一個功能是能夠捕獲子運算式,放在“()”之間的任何文本,在被捕獲後都能用於後面的匹配處理。
模式 |
字串 |
捕獲 |
^(hello|hi)(sir|mister)$ |
hello sir |
$1 = hello $2 = sir |
^(.*)$ |
nginx rocks |
$1 = nginx rocks |
^(.{1,3})([0-9]{1,4})([?!]{1,2})$ |
abc1234?! |
$1 = abc $2 = 1234 $3 = ?! |