Regular Expression 可以拿來解決什麼問題?

Search, Replace, Validate, Reformat

 

普通字元

/a/   (通常使用兩個/來將中間的regular expression包起來)

This is an apple

 

/is/

This is an apple

 

特殊字元 [\^$.|?*+()

(遇到特殊符號前面要加個\來識別)

/if\(true/

if(true){ doSomething() }

 

/1\+2=3/

1+2=3

 

任意字元 (. 表示任意字元,包含空白)

/a.man/

I'm a man

 

/.a/

A banana

 

多個字元

/[aA]/

A apple

(中括號[ ]刮起來就是一個字元,這個字元可以是a或A)

 

/[aeiou]/

There is a apple

 

/[a-z]/  (match所有小寫英文字母)

There is a apple

 

/[a-zA-Z]/

I'm 20 years old

 

/[5-8]/

0980987163

 

/[^a]/  (不是a的字元)

There is a apple

 

/[^0-9]/

I'm 20 years old

 

多個字元縮寫

\d - digit[0-9]

\w - word[A-Za-z0-9_]

\s - space[\n\r\t]

 

/\we/

There is a apple

 

/\d\d/

I'm 20 years old

 

\D - non-digit[^\d]

\W - non-word[^\w]

\S - non-space[^\s]

 

/\D/

1+2=3

 

/\W/

I'm 20 years old

 

出現次數

*   任意次數

+  至少一次

?   零或一次

 

/l*/

Hello World

 

/n?a/  (前面有沒有一個n都沒關係,後面接一個a)

banana

 

{次數}

{最少次數, 最多次數}

 

/l{2}/

Hello World

 

/l{1,}/

Hello World

 

頭尾

^ 開頭

$ 結尾

 

/^He/

Hello Hello

 

/llo$/

Hello Hello

 

/^He.*llo$/  (開頭是He, 結尾是llo, 中間是任意字元, 任意次數)

Hello Hello

 

或 |

 

/and|android/

ios and android  (只要滿足一個條件就不會在往下比對)

 

/android|and/

ios and android

 

常用例子

西元生日 /^[1-9]\d{3}-\d{2}-\d{2}$/ (第一個字不能是0) "1996-08-06"
身分證字號 /^[A-Z]\d{9}$/ "A123456789"
Gmail信箱 /^\w+@gmail\.com$/ "test@gmail.com"
四則運算 /^[\d\+\-\*\/]*$/ "1+6/3-2"

       

邊界比對

在一開始的時候我們看到這個例子

/is/

This is an apple

只要找到is都會被比對到

如果我今天只要比對的是is, 不希望This被比對到

就可以這樣寫:

/\bis\b/

This is an apple

 

把比對到的字元對應的字挑出來

例如: This is an apple

比對到 /a/ 的話我們就要比 an 和 apple也挑出來

那就會這樣寫:

/\S*a\S.*/  (左邊的任意字元但不能為空白,和右邊的任意字元但不能為空白)

或是

/\w*a\w*/  

This is an apple

 

 

Ref:

[1] https://www.youtube.com/watch?v=xrMH9uMNGt8&list=LL&index=6&t=2587s

arrow
arrow

    Mark Zhang 發表在 痞客邦 留言(0) 人氣()