Regular Expression
字串處理的瑞士軍刀
關於我
盧承億 Larry Lu
擅長 React.js、Node.js,略懂 iOS
在 Tutorney 擔任 Full Stack Developer
Github: @Larry850806
Regex 是什麼
^(?:(?=.*[a-z])(?:(?=.*[A-Z])(?=.*[\d\W])|(?=.*\W)(?=.*\d))|(?=.*\W)(?=.*[A-Z])(?=.*\d)).{8,}$
(^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,32}$)?(^(?=.*\d)(?=.*[a-z])(?=.*[@#$%^&+=]).{8,32}$)?(^(?=.*\d)(?=.*[A-Z])(?=.*[@#$%^&+=]).{8,32}$)?(^(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=]).{8,32}$)?
reg[ular] expr[essio]n
學會 Regular Expression 可以幹嘛
.Search
.Replace
.Validate
.Reformat
用 Regular Expression 的好處
.語法精簡(精簡到我都快看不懂了)
.速度非常快
.有很多工具都支援 Regular Expression
普通字元
This is a apple
/a/
/is/
This is a apple
特殊字元
/if \(true/
if (true) { doSomething() }
[\^$.|?*+()
/1\+2=3/
1+2=3
任意字元
/a.man/
I'm a man
/.a/
A banana
多個字元
/[aA]/
A apple
/[aeiou]/
There is a apple
多個字元
/[a-z]/
There is a apple
/[a-zA-Z]/
I'm 20 years old.
/[5-8]/
0980987163
多個字元
/[^a]/
There is a apple
/[^0-9]/
I'm 20 years old.
多個字元縮寫
/\we/
There is a apple
/\d\d/
I'm 20 years old.
\d - digit [0-9]
\w - word [A-Za-z0-9_]
\s - space [ \n\r\t]
多個字元縮寫
/\D/
1 + 2 = 3
/\W/
I'm 20 years old.
\D - non-digit [^\d]
\W - non-word [^\w]
\S - non-space [^\s]
出現次數
/l*/
Hello World
/n?a/
banana
* - 任意次數
+ - 至少一次
? - 零或一次
出現次數
/l{2}/
Hello World
/l{1,}/
Hello World
{最少次數,最多次數}
{次數}
頭尾
/^He/
Hello Hello
/llo$/
Hello Hello
^ - 開頭
$ - 結尾
/^He.*llo$/
Hello Hello
或
/and|android/
iOS and android
/android|and/
iOS and android
常用例子
/^[1-9]\d{3}-\d{2}-\d{2}$/ | 西元生日 | "1996-08-06" |
/^[A-Z]\d{9}$/ | 身分證字號 | "A123456789" |
/^\w+@gmail\.com$/ | Gmail 信箱 | "test@gmail.com" |
/^[\d\+\-\*\/]*$/ | 四則運算式 | "1+6/3-2" |
字串取代
'baNanA'.replace(/na/gi, 'NA') // 'baNANA'
'banana'.replace(/na/, 'NA') // 'baNAna'
'banaNA'.replace(/NA/, 'na') // 'banana'
'banana'.replace(/n.*/, 'NA') // 'baNA'
'banana'.replace(/n./, 'NA') // 'baNAna'
'banana'.replace(/na/g, 'NA') // 'baNANA'
選取
'apple'.match(/(a.)(p.)e/)
// $1 = 'ap'
// $2 = 'pl'
'apple'.replace(/(a.)(p.)e/, '$1$2') // 'appl'
'apple'.replace(/(a.)(p.)e/, '$1$1') // 'apap'
'banana'.match(/(.)(a)/g)
// $1 = ['b', 'n', 'n']
// $2 = ['a', 'a', 'a']
'banana'.replace(/(.)(a)/g, '$1$2') // 'banana'
'banana'.replace(/(.)(a)/g, '$1') // 'bnn'
例子
'2017/05/16'.match(/(.*)\/(.*)\/(.*)/)
// [ '2017/05/16', '2017', '05', '16' ]
JSON.parse(
'2017/05/16'.replace(
/(.*)\/(.*)\/(.*)/,
'{ "year": "$1", "month": "$2", "day": "$3" }'
)
)
// { year: '2017', month: '05', day: '16' }
在 VSCode 中使用 regex 取代字串
使用 grep 搭配 regex 篩選檔案
Regular Expression
By Larry Lu
Regular Expression
- 1,078