Regular Expressions(比對的網站)
Regular Expressions(符號)

有分pattern 和 flag

從開頭找


^
# ex.
# 從開頭找3個數字
# ^\d{3}
124679 # 124

匹配幾個數字


# 匹配3個數字
\d{3}

# 除了數字外
\D


匹配尾部


$
# ex
# 匹配尾部4個數字
# \d{4}$
347859 # 7859


特殊符號


# 字元種類
# []內的只能匹配一次
[]
# ex
[ab] 

# input: abc
# output: ab

# input: bac
# output: ba


# 否定[]內的字元種類
[^]
# ex
[^ab]

# input: abc
# output: c

# input: bac
# output: c

#初始符號
^
# ex
^a

# input: abc
# output: a

# input: bac
# output: 

#結束符號
$
# ex
c$

# input: abc
# output: c

# input: bac
# output: c
# +
匹配到一次就會盡可能繼續匹配
# ex
a+
# input: aaaaaabcccs
# output: aaaaaa # 盡可能找a下去
# *
#匹配次數可以是0~無限次
# ex
ab*
# 匹配到a, 則b可以是沒有

# input: acbb
# output: a

# input: abbbbb
# output: abbbbb
# ?
# 匹配次數可以是0次或1次
# ex
ab?

# input: abbbbbbc
# output: ab

# input: accccv
# output: a
# 有次數限制
# ex
ab{2,3}

# input: abbccc
# output: abb

# input: ab
# output: 

# {2,}
# 2次到無限次的意思
# or
# ex
ab|c


# input: abbbbb
# output: ab

#input: acsd
# output: c

跳脫符號\


# /不能使用, 則可以使用\
\/


匹配字母數字底線


\w+

# 相反(包含換行)
\W+


空格字元和換行


# 包含tab及一些特殊的空白
\s+

匹配換行以外的字元.


.

flag


# global 全域模式
g

# multiline
m

# case insensitive 忽略大小寫
i

# singleline 單行模式
s

練習題

Capture Group

() 掛號起來的的內容可以被Group顯示

<script src=['"]([^'"]+)['"]>\s*</script>


shy group

問號冒號
不會去group那個內容

(?:)


Backreferences


var str = 'abc=abc,def=def,abc=def,def=abc'
var regexp = /(abc|def)=\1/g;
bar result = str.match(regexp);

console.log(result[0]); // "abc=abc"
console.log(result[1]); // "def=def"

Lookaround (左右合樣)

比對左右有沒有相符合的字

# 驗證至少6位有大小寫加數字的密碼
# 範例
^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,30}$


Greedy Mode


# 盡可能找出最長a到b之間的字串
a.*b
Non-Greedy Mode

# 只找第一個到a到b的字串
a.*?b

email regex rfc822

標準版