正則表達式 (regex) 的快速參考,包括符號、范圍、分組、斷言和一些示例模式,以幫助您入門。
這是開始使用正則表達式(Regex)的快速備忘單。
范例 | 說明 |
---|---|
[abc] | 單個字符:a 、b 或 c |
[^abc] | 一個字符,除了:a 、b 或 c |
[a-z] | 范圍內的字符:a-z |
[^a-z] | 不在范圍內的字符:a-z |
[0-9] | 范圍內的數字:0-9 |
[a-zA-Z] | 范圍內的字符:a-z 或 A-Z |
[a-zA-Z0-9] | 范圍內的字符:a-z 、A-Z 或 0-9 |
范例 | 說明 |
---|---|
a? | 零個或一個a |
a* | 零個或多個 a |
a+ | 一個或多個a |
[0-9]+ | 0-9 中的一個或多個 |
a{3} | 正好 3 個 a |
a{3,} | 3個或更多的a |
a{3,6} | a 的 3 到 6 之間 |
a* | 貪心量詞 |
a*? | 惰性量詞 |
a*+ | 占有量詞 |
使用 \
轉義這些特殊字符
范例 | 說明 |
---|---|
. | 任何單個字符 |
\s | 任何空白字符 |
\S | 任何非空白字符 |
\d | 任何數字,與 [0-9] 相同 |
\D | 任何非數字,與 [^0-9] 相同 |
\w | 任何單詞字符 |
\W | 任何非單詞字符 |
\X | 任何 Unicode 序列,包括換行符 |
\C | 匹配一個數據單元 |
\R | Unicode 換行符 |
\v | 垂直空白字符 |
\V | \v 的否定 - 除了換行符和垂直制表符之外的任何內容 |
\h | 水平空白字符 |
\H | \h 的否定 |
\K | 重置匹配 |
\n | 匹配第 n 個子模式 |
\pX | Unicode 屬性 X |
\p{...} | Unicode 屬性或腳本類別 |
\PX | \pX 的否定 |
\P{...} | \p 的否定 |
\Q...\E | 引用;視為文字 |
\k<name> | 匹配子模式name |
\k'name' | 匹配子模式name |
\k{name} | 匹配子模式name |
\gn | 匹配第 n 個子模式 |
\g{n} | 匹配第 n 個子模式 |
\g<n> | 遞歸第 n 個捕獲組 |
\g'n' | 遞歸第 n 個捕獲組。 |
\g{-n} | 匹配第 n 個相對前一個子模式 |
\g<+n> | 遞歸第 n 個相對即將到來的子模式 |
\g'+n' | 匹配第 n 個相對即將到來的子模式 |
\g'letter' | 遞歸命名捕獲組 字母 |
\g{letter} | 匹配先前命名的捕獲組 字母 |
\g<letter> | 遞歸命名捕獲組 字母 |
\xYY | 十六進制字符 YY |
\x{YYYY} | 十六進制字符 YYYY |
\ddd | 八進制字符ddd |
\cY | 控制字符 Y |
[\b] | 退格字符 |
\ | 使任何字符文字 |
范例 | 說明 |
---|---|
\G | 比賽開始 |
^ | 字符串的開始 |
$ | 字符串結束 |
\A | 字符串的開始 |
\Z | 字符串結束 |
\z | 字符串的絕對結尾 |
\b | 一個詞的邊界 |
\B | 非單詞邊界 |
范例 | 說明 |
---|---|
\0 | 完整的比賽內容 |
\1 | 捕獲組 1 中的內容 |
$1 | 捕獲組 1 中的內容 |
${foo} | 捕獲組 foo 中的內容 |
\x20 | 十六進制替換值 |
\x{06fa} | 十六進制替換值 |
\t | 標簽 |
\r | 回車 |
\n | 新隊 |
\f | 換頁 |
\U | 大寫轉換 |
\L | 小寫轉換 |
\E | 終止任何轉換 |
范例 | 說明 |
---|---|
(...) | 捕獲所有封閉的東西 |
(a|b) | 匹配 a 或 b |
(?:...) | 匹配隨附的所有內容 |
(?>...) | 原子組(非捕獲) |
(?|...) | 重復的子模式組號 |
(?#...) | 注解 |
(?'name'...) | 命名捕獲組 |
(?<name>...) | 命名捕獲組 |
(?P<name>...) | 命名捕獲組 |
(?imsxXU) | 內聯修飾符 |
(?(DEFINE)...) | 在使用它們之前預定義模式 |
:- | - |
---|---|
(?(1)yes|no) | 條件語句 |
(?(R)yes|no) | 條件語句 |
(?(R#)yes|no) | 遞歸條件語句 |
(?(R&name)yes|no) | 條件語句 |
(?(?=...)yes|no) | 有條件的前瞻 |
(?(?<=...)yes|no) | 有條件的往后看 |
:- | - |
---|---|
(?R) | 遞歸整個模式 |
(?1) | 遞歸第一個子模式 |
(?+1) | 遞歸第一個相對子模式 |
(?&name) | 遞歸子模式name |
(?P=name) | 匹配子模式name |
(?P>name) | 遞歸子模式name |
:- | - |
---|---|
g | 全部 |
m | 多行 |
i | 不區分大小寫 |
x | 忽略空格 |
s | 單線 |
u | 統一碼 |
X | 擴展 |
U | 不貪心 |
A | 錨 |
J | 重復的組名 |
d | 結果包含捕獲組子字符串開始和結束的索引 |
:- | - |
---|---|
(?=...) | 正先行斷言 |
(?!...) | 負先行斷言 |
(?<=...) | 正后發斷言 |
(?<!...) | 負后發斷言 |
?= | 正先行斷言-存在 |
?! | 負先行斷言-排除 |
?<= | 正后發斷言-存在 |
?<! | 負后發斷言-排除 |
零寬度斷言 允許您在主模式之前(向后看)或之后(lookahead)匹配一個組,而不會將其包含在結果中。
字符類 | 如同 | 意義 |
---|---|---|
[[:alnum:]] | [0-9A-Za-z] | 字母和數字 |
[[:alpha:]] | [A-Za-z] | 字母 |
[[:ascii:]] | [\x00-\x7F] | ASCII 碼 0-127 |
[[:blank:]] | [\t ] | 僅空格或制表符 |
[[:cntrl:]] | [\x00-\x1F\x7F] | 控制字符 |
[[:digit:]] | [0-9] | 十進制數字 |
[[:graph:]] | [[:alnum:][:punct:]] | 可見字符(不是空格) |
[[:lower:]] | [a-z] | 小寫字母 |
[[:print:]] | [ -~] == [ [:graph:]] | 可見字符 |
[[:punct:]] | [!"#$%&’()*+,-./:;<=>?@[]^_`{|}~] | 可見標點符號 |
[[:space:]] | [\t\n\v\f\r ] | 空白 |
[[:upper:]] | [A-Z] | 大寫字母 |
[[:word:]] | [0-9A-Za-z_] | 單詞字符 |
[[:xdigit:]] | [0-9A-Fa-f] | 十六進制數字 |
[[:<:]] | [\b(?=\w)] | 詞的開頭 |
[[:>:]] | [\b(?<=\w)] | 詞尾 |
:- | - |
---|---|
(*ACCEPT) | 控制動詞 |
(*FAIL) | 控制動詞 |
(*MARK:NAME) | 控制動詞 |
(*COMMIT) | 控制動詞 |
(*PRUNE) | 控制動詞 |
(*SKIP) | 控制動詞 |
(*THEN) | 控制動詞 |
(*UTF) | 圖案修飾符 |
(*UTF8) | 圖案修飾符 |
(*UTF16) | 圖案修飾符 |
(*UTF32) | 圖案修飾符 |
(*UCP) | 圖案修飾符 |
(*CR) | 換行修飾符 |
(*LF) | 換行修飾符 |
(*CRLF) | 換行修飾符 |
(*ANYCRLF) | 換行修飾符 |
(*ANY) | 換行修飾符 |
\R | 換行修飾符 |
(*BSR_ANYCRLF) | 換行修飾符 |
(*BSR_UNICODE) | 換行修飾符 |
(*LIMIT_MATCH=x) | 正則表達式引擎修飾符 |
(*LIMIT_RECURSION=d) | 正則表達式引擎修飾符 |
(*NO_AUTO_POSSESS) | 正則表達式引擎修飾符 |
(*NO_START_OPT) | 正則表達式引擎修飾符 |
范例 | 說明 |
---|---|
ring | 匹配 |
. | 匹配 |
h.o | 匹配 |
ring\? | 匹配 |
\(quiet\) | 匹配 |
c:\\windows | 匹配 |
使用 \
搜索這些特殊字符:
[ \ ^ $ . | ? * + ( ) { }
范例 | 說明 |
---|---|
\w | “單詞”字符 (字母、數字或下劃線) |
\d | 數字 |
\s | 空格 (空格、制表符、vtab、換行符) |
\W, \D, or \S | 不是單詞、數字或空格 |
[\D\S] | 表示不是數字或空格,兩者都匹配 |
[^\d\s] | 禁止數字和空格 |
范例 | 說明 |
---|---|
colou?r | 匹配 |
[BW]ill[ieamy's]* | 匹配 |
[a-zA-Z]+ | 匹配 1 個或多個字母 |
\d{3}-\d{2}-\d{4} | 匹配 SSN |
[a-z]\w{1,7} | 匹配 UW NetID |
范例 | 說明 |
---|---|
cat|dog | 匹配 |
id|identity | 匹配 |
identity|id | 匹配 |
當替代品重疊時,命令從長到短
范例 | 說明 |
---|---|
[aeiou] | 匹配任何元音 |
[^aeiou] | 匹配一個非元音 |
r[iau]ng | 匹配 |
gr[ae]y | 匹配 |
[a-zA-Z0-9] | 匹配任何字母或數字 |
在 [ ]
中總是轉義 . \ ]
有時是 ^ - .
范例 | 說明 |
---|---|
* + {n,} greedy | 盡可能匹配 |
<.+> | 在 |
*? +? {n,}? lazy | 盡可能少匹配 |
<.+?> | 在 < |
范例 | 說明 |
---|---|
\b | “單詞”邊緣(非“單詞”字符旁邊) |
\bring | 單詞以“ring”開頭,例如 |
ring\b | 單詞以“ring”結尾,例如 |
\b9\b | 匹配單個數字 |
\b[a-zA-Z]{6}\b | 匹配 6 個字母的單詞 |
\B | 不是字邊 |
\Bring\B | 匹配 |
^\d*$ | 整個字符串必須是數字 |
^[a-zA-Z]{4,20}$ | 字符串必須有 4-20 個字母 |
^[A-Z] | 字符串必須以大寫字母開頭 |
[\.!?"')]$ | 字符串必須以終端標點結尾 |
范例 | 說明 |
---|---|
(?i) [a-z]*(?-i) | 忽略大小寫開/關 |
(?s) .*(?-s) | 匹配多行(導致 . 匹配換行符) |
(?m) ^.*;$(?-m) | |
(?x) | #free-spacing 模式,此 EOL 注釋被忽略 |
(?-x) | 自由空間模式關閉 |
/regex/ismx | 修改整個字符串的模式 |
范例 | 說明 |
---|---|
(in|out)put | 匹配 |
\d{5}(-\d{4})? | 美國郵政編碼 (“+ 4”可選) |
如果組后匹配失敗,解析器會嘗試每個替代方案。
可能導致災難性的回溯。
范例 | 說明 |
---|---|
(to) (be) or not \1 \2 | 匹配 |
([^\s])\1{2} | 匹配非空格,然后再相同兩次 ? |
\b(\w+)\s+\1\b | 匹配雙字 |
范例 | 說明 |
---|---|
on(?:click|load) | 快于:on(click|load) |
盡可能使用非捕獲或原子組
范例 | 說明 |
---|---|
(?>red|green|blue) | 比非捕獲更快 |
(?>id|identity)\b | 匹配 |
"id" 匹配,但 \b
在原子組之后失敗,
解析器不會回溯到組以重試“身份”
如果替代品重疊,請從長到短命令。
范例 | 說明 |
---|---|
(?= ) | 向前看,如果你能提前找到 |
(?! ) | 向前看,如果你找不到前面 |
(?<= ) | 向后看,如果你能找到后面 |
(?<! ) | 向后看,如果你找不到后面 |
\b\w+?(?=ing\b) | 匹配 |
\b(?!\w+ing\b)\w+\b | 不以“ing”結尾的單詞 |
(?<=\bpre).*?\b | 匹配 pre |
\b\w{3}(?<!pre)\w*?\b | 不以“pre”開頭的詞 |
\b\w+(?<!ing)\b | 匹配不以“ing”結尾的單詞 |
匹配 Mr.
或 Ms.
如果單詞 her
稍后在字符串中
M(?(?=.*?\bher\b)s|r)\.
需要環顧 IF
條件
表達式 | 匹配示例 |
---|---|
the | The fat cat sat on the mat. |
The | The fat cat sat on the mat. |
由字母t
開始,接著是h
,再接著是e
.
表達式 | 匹配示例 |
---|---|
.ar | The car par ked in the gar age. |
表達式.ar
匹配一個任意字符后面跟著是a
和r
的字符串
表達式 | 匹配示例 |
---|---|
.ar | The car par gar age. |
ar[.] | A garage is a good place to park a car . |
方括號的句號就表示句號。表達式 ar[.]
匹配 ar.
字符串
表達式 | 匹配示例 |
---|---|
[^c]ar | The car par ked in the gar age. |
表達式 [^c]ar
匹配一個后面跟著 ar
的除了c
的任意字符。
*
號表達式 | 匹配示例 |
---|---|
[a-z]* | The car parked in the garage |
\s*cat\s* | The fat cat sat on the concat enation. |
表達式 [a-z]*
匹配一個行中所有以小寫字母開頭的字符串。
+
號表達式 | 匹配示例 |
---|---|
c.+t | The fat cat sat on the mat . |
表達式 c.+t
匹配以首字母c開頭以t結尾,中間跟著至少一個字符的字符串。
?
號表達式 | 匹配示例 |
---|---|
[T]he | The car is parked in the garage. |
[T]?he | The car is parked in the garage. |
表達式 [T]?he
匹配字符串 he
和 The
。
{}
號表達式 | 匹配示例 |
---|---|
[0-9]{2,3} | The number was 9.999 7 but we rounded it off to 10 .0. |
[0-9]{2,} | The number was 9.9997 but we rounded it off to 10 .0. |
[0-9]{3} | The number was 9.999 7 but we rounded it off to 10.0. |
(...)
特征標群表達式 | 匹配示例 |
---|---|
(c|g|p)ar | The car is par ked in the gar age. |
表達式 (c|g|p)ar
匹配 car
或 gar
或 par
。 注意 \
是在 Markdown 中為了不破壞表格轉義 |
。
|
或運算符表達式 | 匹配示例 |
---|---|
(T|t)he|car | The car is parked in the garage. |
表達式 (T|t)he|car
匹配 (T|t)he
或 car
表達式 | 匹配示例 |
---|---|
(f|c|m)at\.? | The fat cat sat on the mat. |
如果想要匹配句子中的 .
則要寫成 \.
以下這個例子 \.?
是選擇性匹配.
匹配指定開頭或結尾的字符串就要使用到錨點。
^
號 (符串的開頭)表達式 | 匹配示例 |
---|---|
(T|t)he | The car is parked in the garage. |
^(T|t)he | The car is parked in the garage. |
$
號 (否是最后一個)表達式 | 匹配示例 |
---|---|
(at\.) | The fat cat. sat. on the mat. |
(at\.)$ | The fat cat. sat. on the mat. |
簡寫 | 描述 |
---|---|
. | 除換行符外的所有字符 |
\w | 匹配所有字母數字 等同于 [a-zA-Z0-9_] |
\W | 匹配所有非字母數字,即符號 等同于: [^\w] |
\d | 匹配數字: [0-9] |
\D | 匹配非數字: [^\d] |
\s | 匹配所有空格字符 等同于: [\t\n\f\r\p{Z}] |
\S | 匹配所有非空格字符: [^\s] |
\f | 匹配一個換頁符 |
\n | 匹配一個換行符 |
\r | 匹配一個回車符 |
\t | 匹配一個制表符 |
\v | 匹配一個垂直制表符 |
\p | 匹配 CR/LF(等同于 \r\n )用來匹配 DOS 行終止符 |
正則表達式提供一些常用的字符集簡寫。
?=...
正先行斷言表達式 | 匹配示例 |
---|---|
(T|t)he(?=\sfat) | The fat cat sat on the mat. |
The
和 the
后面緊跟著 (空格)fat
。
?!...
負先行斷言表達式 | 匹配示例 |
---|---|
(T|t)he(?!\sfat) | The fat cat sat on the mat. |
匹配 The
和 the
,且其后不跟著 (空格)fat
。
?<= ...
正后發斷言表達式 | 匹配示例 |
---|---|
(?<=(T|t)he\s)(fat|mat) | The fat cat sat on the mat . |
匹配 fat
和 mat
,且其前跟著 The
或 the
。
?<!...
負后發斷言表達式 | 匹配示例 |
---|---|
(?<!(T|t)he\s)(cat) | The cat sat on cat . |
匹配 cat
,且其前不跟著 The
或 the
。
表達式 | 匹配示例 |
---|---|
The | The fat cat sat on the mat. |
/The/gi | The fat cat sat on the mat. |
修飾語 i
用于忽略大小寫,g
表示全局搜索。
表達式 | 匹配示例 |
---|---|
/.(at)/ | The fat cat sat on the mat. |
/.(at)/g | The fat cat sat on the mat . |
表達式 /.(at)/g
表示搜索 任意字符(除了換行)+ at
,并返回全部結果。
表達式 | 匹配示例 |
---|---|
/.at(.)?$/ | The fat cat sat on the mat . |
/.at(.)?$/gm | The fat cat sat on the mat . |
表達式 | 匹配示例 |
---|---|
/(.*at)/ | The fat cat sat on the mat . |
/(.*?at)/ | The fat cat sat on the mat. |
導入正則表達式模塊
import re
>>> sentence = 'This is a sample string'
>>> bool(re.search(r'this', sentence, flags=re.I))
True
>>> bool(re.search(r'xyz', sentence))
False
>>> re.findall(r'\bs?pare?\b', 'par spar apparent spare part pare')
['par', 'spar', 'spare', 'pare']
>>> re.findall(r'\b0*[1-9]\d{2,}\b', '0501 035 154 12 26 98234')
['0501', '154', '98234']
>>> m_iter = re.finditer(r'[0-9]+', '45 349 651 593 4 204')
>>> [m[0] for m in m_iter if int(m[0]) < 350]
['45', '349', '4', '204']
>>> re.split(r'\d+', 'Sample123string42with777numbers')
['Sample', 'string', 'with', 'numbers']
>>> ip_lines = "catapults\nconcatenate\ncat"
>>> print(re.sub(r'^', r'* ', ip_lines, flags=re.M))
* catapults
* concatenate
* cat
>>> pet = re.compile(r'dog')
>>> type(pet)
<class '_sre.SRE_Pattern'>
>>> bool(pet.search('They bought a dog'))
True
>>> bool(pet.search('A cat crossed their path'))
False
函數 | 說明 |
---|---|
re.findall | 返回包含所有匹配項的列表 |
re.finditer | 返回一個可迭代的匹配對象 (每個匹配一個) |
re.search | 如果字符串中的任何位置存在匹配項,則返回 Match 對象 |
re.split | 返回一個列表,其中字符串在每次匹配時被拆分 |
re.sub | 用字符串替換一個或多個匹配項 |
re.compile | 編譯正則表達式模式供以后使用 |
re.escape | 返回所有非字母數字反斜杠的字符串 |
:- | - | - |
---|---|---|
re.I | re.IGNORECASE | 忽略大小寫 |
re.M | re.MULTILINE | 多行 |
re.L | re.LOCALE | 使 \w 、\b 、\s locale 依賴 |
re.S | re.DOTALL | 點匹配所有 (包括換行符) |
re.U | re.UNICODE | 使 \w 、\b 、\d 、\s unicode 依賴 |
re.X | re.VERBOSE | 可讀風格 |
:- | :- |
---|---|
dotAll | 是否使用了 s 修飾符 |
flags | 返回標志的字符串 |
global | 是否使用了 g (全部)修飾符 |
hasIndices | 是否使用了 d 修飾符 |
ignoreCase | 匹配文本的時候是否忽略大小寫 i |
multiline | 是否進行多行搜索 m |
lastIndex | 該索引表示從哪里開始下一個匹配 |
source | 正則表達式的文本 |
sticky | 搜索是否是 sticky |
unicode | Unicode 功能是否開啟 |
:- | :- |
---|---|
match() | 獲取匹配結果 |
matchAll() | 所有匹配項 |
replace() | 替換所有符合正則模式的匹配項 |
search() | 搜索以取得匹配正則模式的項 |
split() | 切割字符串返回字符串數組 |
compile() | (重新)編譯正則表達式 |
exec() | 指定字符串中執行一個搜索匹配 |
test() | 正則表達式與指定的字符串是否匹配 |
toString() | 返回該正則表達式的字符串 |
let textA = 'I like APPles very much';
let textB = 'I like APPles';
let regex = /apples$/i
console.log(regex.test(textA)); // false
console.log(regex.test(textB)); // true
let text = 'I like APPles very much';
let regexA = /apples/;
let regexB = /apples/i;
console.log(text.search(regexA)); // -1
console.log(text.search(regexB)); // 7
let text = 'Do you like apples?';
let regex= /apples/;
// Output: apples
console.log(regex.exec(text)[0]);
// Output: Do you like apples?
console.log(regex.exec(text).input);
let text = 'Here are apples and apPleS';
let regex = /apples/gi;
// Output: [ "apples", "apPleS" ]
console.log(text.match(regex));
let text = 'This 593 string will be brok294en at places where d1gits are.';
let regex = /\d+/g
// Output: [ "This ", " string will be brok", "en at places where d", "gits are." ]
console.log(text.split(regex))
let regex = /t(e)(st(\d?))/g;
let text = 'test1test2';
let array = [...text.matchAll(regex)];
// Output: ["test1", "e", "st1", "1"]
console.log(array[0]);
// Output: ["test2", "e", "st2", "2"]
console.log(array[1]);
let text = 'Do you like aPPles?';
let regex = /apples/i
// Output: Do you like mangoes?
let result = text.replace(regex, 'mangoes');
console.log(result);
/d/s.dotAll; // => true
/d/g.global; // => true
/d/ig.flags; // => "gi"
/d/d.hasIndices; // => true
/d/i.ignoreCase; // => true
let s = "Please yes\nmake my day!";
s.match(/yes[^]*day/);
// 返回 'yes\nmake my day'
let regex = /apples/gi;
let text = 'Here are apples and apPleS';
text.replaceAll(regex, "mangoes");
// 返回: Here are mangoes and mangoes
:- | - |
---|---|
preg_match() | 執行正則表達式匹配 |
preg_match_all() | 執行全局正則表達式匹配 |
preg_replace_callback() | 使用回調執行正則表達式搜索和替換 |
preg_replace() | 執行正則表達式搜索和替換 |
preg_split() | 按正則表達式模式拆分字符串 |
preg_grep() | 返回與模式匹配的數組條目 |
$str = "Visit Microsoft!";
$regex = "/microsoft/i";
// Output: Visit QuickRef!
echo preg_replace($regex, "QuickRef", $str);
$str = "Visit QuickRef";
$regex = "#quickref#i";
// Output: 1
echo preg_match($regex, $str);
$regex = "/[a-zA-Z]+ (\d+)/";
$input_str = "June 24, August 13, and December 30";
if (preg_match_all($regex, $input_str, $matches_out)) {
// Output: 2
echo count($matches_out);
// Output: 3
echo count($matches_out[0]);
// Output: Array("June 24", "August 13", "December 30")
print_r($matches_out[0]);
// Output: Array("24", "13", "30")
print_r($matches_out[1]);
}
$arr = ["Jane", "jane", "Joan", "JANE"];
$regex = "/Jane/";
// Output: Jane
echo preg_grep($regex, $arr);
$str = "Jane\tKate\nLucy Marion";
$regex = "@\s@";
// Output: Array("Jane", "Kate", "Lucy", "Marion")
print_r(preg_split($regex, $str));
Pattern p = Pattern.compile(".s", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher("aS");
boolean s1 = m.matches();
System.out.println(s1); // Outputs: true
boolean s2 = Pattern.compile("[0-9]+").matcher("123").matches();
System.out.println(s2); // Outputs: true
boolean s3 = Pattern.matches(".s", "XXXX");
System.out.println(s3); // Outputs: false
:- | - |
---|---|
CANON_EQ | 規范等價 |
CASE_INSENSITIVE | 不區分大小寫的匹配 |
COMMENTS | 允許空格和注釋 |
DOTALL | 圓點模式 |
MULTILINE | 多行模式 |
UNICODE_CASE | Unicode 感知大小寫折疊 |
UNIX_LINES | Unix 行模式 |
還有更多方法...
替換句子:
String regex = "[A-Z\n]{5}$";
String str = "I like APP\nLE";
Pattern p = Pattern.compile(regex, Pattern.MULTILINE);
Matcher m = p.matcher(str);
// Outputs: I like Apple!
System.out.println(m.replaceAll("pple!"));
所有匹配的數組:
String str = "She sells seashells by the Seashore";
String regex = "\\w*se\\w*";
Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(str);
List<String> matches = new ArrayList<>();
while (m.find()) {
matches.add(m.group());
}
// Outputs: [sells, seashells, Seashore]
System.out.println(matches);
函數名稱 | 說明 |
---|---|
REGEXP | 字符串是否匹配正則表達式 |
REGEXP_INSTR() | 匹配正則表達式的子字符串的起始索引 (注意:僅限 MySQL 8.0+) |
REGEXP_LIKE() | 字符串是否匹配正則表達式 (注意:僅 MySQL 8.0+) |
REGEXP_REPLACE() | 替換匹配正則表達式的子字符串 (注意:僅限 MySQL 8.0+) |
REGEXP_SUBSTR() | 返回匹配正則表達式的子字符串 (注意:僅 MySQL 8.0+) |
expr REGEXP pat
mysql> SELECT 'abc' REGEXP '^[a-d]';
1
mysql> SELECT name FROM cities WHERE name REGEXP '^A';
mysql> SELECT name FROM cities WHERE name NOT REGEXP '^A';
mysql> SELECT name FROM cities WHERE name REGEXP 'A|B|R';
mysql> SELECT 'a' REGEXP 'A', 'a' REGEXP BINARY 'A';
1 0
REGEXP_REPLACE(expr, pat, repl[, pos[, occurrence[, match_type]]])
mysql> SELECT REGEXP_REPLACE('a b c', 'b', 'X');
a X c
mysql> SELECT REGEXP_REPLACE('abc ghi', '[a-z]+', 'X', 1, 2);
abc X
REGEXP_SUBSTR(expr, pat[, pos[, occurrence[, match_type]]])
mysql> SELECT REGEXP_SUBSTR('abc def ghi', '[a-z]+');
abc
mysql> SELECT REGEXP_SUBSTR('abc def ghi', '[a-z]+', 1, 3);
ghi
REGEXP_LIKE(expr, pat[, match_type])
mysql> SELECT regexp_like('aba', 'b+')
1
mysql> SELECT regexp_like('aba', 'b{2}')
0
mysql> # i: case-insensitive
mysql> SELECT regexp_like('Abba', 'ABBA', 'i');
1
mysql> # m: multi-line
mysql> SELECT regexp_like('a\nb\nc', '^b$', 'm');
1
REGEXP_INSTR(expr, pat[, pos[, occurrence[, return_option[, match_type]]]])
mysql> SELECT regexp_instr('aa aaa aaaa', 'a{3}');
2
mysql> SELECT regexp_instr('abba', 'b{2}', 2);
2
mysql> SELECT regexp_instr('abbabba', 'b{2}', 1, 2);
5
mysql> SELECT regexp_instr('abbabba', 'b{2}', 1, 3, 1);
7