Published on

15分鐘掌握Regular Expression(正規表達式)

Authors
  • avatar
    Name
    走歪的工程師James
    Twitter

相關資源

Regex101: https://regex101.com/

freecodecamp完整教學文章

影片中範例

純文字

My cat is named Felix. My dog's name is Fido. I also have a fish named Finny.

點:.

.可以匹配任意的字元,除了換行

John
Jane
Jason
Jonny
Jacky
Jake

重複組合:+, *, ?

  • +代表重複一次以上
  • *代表重複0次以上
  • ?代表0次或1次
Heeeellooo
Helloooo
Hello
Heeelllooo
Helo

任何數字、字母:\w \d

  • \w代表任何字母、數字
  • \d代表任何數字
Room 101
Suite 202
Floor 3

重複指定次數:

  • {2}代表重複2次
  • {3,}代表重複3次以上
  • {3,5}代表重複3到5次
aaaaaaa
aaa
aaaaaa
a

或:|

  • ab|bc代表配對ab或bc
ab
bc
abc
bcc

多字符選一:[]

  • [abc]代表abc中選一個
  • [a-z]代表a到z中選一個
  • [A-Z]代表A到Z選一個
  • [0-9]代表0到9選一個
abc0
bbc1
cbc2
dbc3
ebc4
fbc5
gbc6
hbc7
The quick brown fox jumps over the lazy dog.

否定字符:[^]

  • [^aeiou]代表aeiou以外的字符
Boys and girls play in the park.

跳脫字元:\

  • \.可以配對字串中的.
Price is $5.99.
Use the code: DISCOUNT10%
Save 20% on your next purchase!

Anchors: ^, $

  • $代表一行的末端
  • ^代表一行的開頭
Hello World Hello
Hello Regex Regex
Hello World

字的邊界:\b

Jane is a great developer.
Janet is a designer.
Jane123
Janet333
1123Jane333

捕獲組:()

  • The (\w+) is \w+.可以把第二個字捕捉起來
  • $1在替代時代表第一個捕捉到的組合
  • (?:)可以使用括號,但不捕捉
The car is red.
The bike is blue.
The boat is green.
green
yellow
blue

應用題

匹配電話號碼

Call us at (555) 123-4567 or (123) 987-6543.

匹配email

Contact us at support@example.com or admin@domain.org.
james.ku@jameskool.com
Jake-kk@gmail.com

替代日期格式

2024-06-08
2024-12-25
2024-01-01