Regex的文法

來源:互聯網
上載者:User

標籤: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 = ?!

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.