正则表达式快速入门正则表达式快速入门正则表达式快速入门正则表达式快速入门
  • 文章
  • 正则表达式
    • 工具
  • 登录
找到的结果: {phrase} (显示: {results_count} 共: {results_count_total})
显示: {results_count} 共: {results_count_total}

加载更多搜索结果...

搜索范围
模糊匹配
搜索标题
搜索内容
发表 admin at 2024年3月5日
类别
  • 正则表达式
标签
正则表达式快速入门
  • 简
  • 繁
  • En
关于正则表达式 » 正则表达式快速入门

欢迎
简介
正则表达式快速入门
正则表达式教程
替换字符串教程
应用程序和语言
正则表达式范例
正则表达式参考
替换字符串参考

正则表达式快速入门

这个快速入门可让您快速了解正则表达式。显然地,这个简短的简介无法解释正则表达式的全部内容。如需详细信息,请参阅正则表达式教程。快速入门中的每个主题都对应教学中的某个主题,因此您可以轻松地在两者之间来回切换。

许多应用程序和编程语言都有自己的正则表达式实作,通常与其他实作略有不同,有时甚至有显著差异。当两个应用程序使用不同的正则表达式实作时,我们会说它们使用不同的「正则表达式风格」。这个快速入门说明了最受欢迎的正则表达式风格所支持的语法。

文本模式和比对

正则表达式,简称 regex,是一种描述一定量文本的模式。在此网站上,正则表达式会以灰色阴影显示为 regex。这实际上是一个完全有效的 regex。这是最基本的模式,仅比对文本 regex。比对会在此网站上以蓝色突显。我们使用「字符串」一词来表示套用正则表达式的文本。字符串会以 绿色 突显。

在正则表达式中具有特殊意义的字符会以各种不同的颜色突显。regex (?x)([Rr]egexp?)\? 以紫色显示元标记,以绿色显示群组,以橘色显示字符类别,以蓝色显示量词和其他特殊标记,并以灰色显示转义字符。

文本字符

最基本的正则表达式包含一个单一的文本字符,例如 a。它会比对字符串中该字符的第一次出现。如果字符串是 Jack is a boy,它会比对 J 之后的 a。

这个正则表达式也可以匹配第二个 a。它只会在您告诉正则表达式引擎在第一次匹配后开始搜索字符串时运行此操作。在文本编辑器中,您可以使用其「寻找下一个」或「向前搜索」功能来运行此操作。在编程语言中,通常有一个独立的功能,您可以调用它来在先前的匹配后继续搜索字符串。

十二个字符在正则表达式中具有特殊意义:反斜线 \、插入符号 ^、美元符号 $、句点或圆点 .、垂直线或管道符号 |、问号 ?、星号或星形 *、加号 +、打开括弧 (、关闭括弧 )、打开方括弧 [ 和打开大括弧 {。这些特殊字符通常称为「元字符」。大多数单独使用时会产生错误。

如果您想在正则表达式中将任何这些字符用作文本,您需要使用反斜线转义它们。如果您想匹配 1+1=2,正确的正则表达式是 1\+1=2。否则,加号具有特殊意义。

深入了解文本字符

不可打印字符

您可以使用特殊字符串行将不可打印字符放入您的正则表达式中。使用 \t 来匹配一个标签字符(ASCII 0x09),\r 来匹配回车(0x0D)和 \n 来匹配换行(0x0A)。更特别的不可打印字符有 \a(铃声,0x07),\e(转义,0x1B),\f(换页,0x0C)和 \v(垂直标签,0x0B)。请记住,Windows 文本文件使用 \r\n 来终止列,而 UNIX 文本文件使用 \n。

如果您的应用程序支持 Unicode,请使用 \uFFFF 或 \x{FFFF} 来插入一个 Unicode 字符。 \u20AC 或 \x{20AC} 匹配欧元货币符号。

如果您的应用程序不支持 Unicode,请使用 \xFF 来通过字符集中的十六进位索引来匹配一个特定字符。 \xA9 在 Latin-1 字符集中匹配版权符号。

所有不可打印字符都可直接用于正则表达式中,或作为字符类别的一部分。

进一步了解不可打印字符

字符类别或字符集

「字符类别」只会比对几个字符中的其中一个。若要比对 a 或 e,请使用 [ae]。您可以在 gr[ae]y 中使用此方法来比对 gray 或 grey。字符类别只会比对单一字符。gr[ae]y 不会比对 graay、graey 或任何类似字符串。字符类别中字符的顺序并不重要。

您可以在字符类别中使用连字号来指定字符范围。[0-9] 会比对 0 到 9 之间的单一数字。您可以使用多个范围。[0-9a-fA-F] 会比对单一十六进位数字,不分大小写。您可以结合范围和单一字符。[0-9a-fxA-FX] 会比对十六进位数字或字母 X。

在打开方括号后输入插入符号会否定字符类别。结果是字符类别会比对不在字符类别中的任何字符。q[^x] 会在 question 中比对 qu。它不会比对 Iraq,因为在 q 之后没有字符供否定的字符类别比对。

进一步了解字符类别

简写字符类别

\d 会比对单一数字字符,\w 会比对「字符字符」(字母数字字符加上底线),而 \s 会比对空白字符(包括标签和换行符号)。简写实际比对的字符取决于您使用的软件。在现代应用程序中,它们包含非英文本母和数字。

深入了解简写字符类别

点号匹配(几乎)任何字符

点号匹配单一字符,换行字符除外。大多数应用程序都有「点号匹配所有」或「单行」模式,让点号匹配任何单一字符,包括换行字符。

gr.y 匹配 gray、grey、gr%y 等。请谨慎使用点号。通常,字符类别或否定字符类别速度更快、更精确。

深入了解点号

锚点

锚点不匹配任何字符。它们匹配位置。 ^ 匹配字符串开头,$ 匹配字符串结尾。大多数正则表达式引擎都有「多行」模式,让 ^ 在任何换行后匹配,$ 在任何换行前匹配。例如,^b 仅匹配 bob 中的第一个 b。

\b 匹配字词边界。字词边界是 \w 可以匹配的字符与 \w 无法匹配的字符之间的位置。如果字符串的第一个和/或最后一个字符是字词字符,\b 也会在字符串开头和/或结尾匹配。 \B 匹配 \b 无法匹配的每个位置。

深入了解锚点

交替

交替是正则表达式中「或」的等效项。 cat|dog 在 About cats and dogs 中匹配 cat。如果再次套用正则表达式,它会匹配 dog。您可以添加任意数量的选项:cat|dog|mouse|fish。

交替具有所有正规运算符中最低的优先级。cat|dog food 符合 cat 或 dog food。若要创建符合 cat food 或 dog food 的正规表达式,您需要将交替选项分组:(cat|dog) food。

深入了解交替

重复

问号使正规表达式中的前一个代币成为选用。 colou?r 符合 colour 或 color。

星号或星号告诉引擎尝试将前一个代币符合零次或多次。加号告诉引擎尝试将前一个代币符合一次或多次。<[A-Za-z][A-Za-z0-9]*> 符合没有任何属性的 HTML 标签。<[A-Za-z0-9]+> 较容易撰写,但会符合无效的标签,例如 <1>。

使用大括号指定特定的重复次数。使用 \b[1-9][0-9]{3}\b 来符合介于 1000 至 9999 之间的数字。\b[1-9][0-9]{2,4}\b 符合介于 100 至 99999 之间的数字。

深入了解量词

贪婪和懒惰重复

重复运算符或量词是贪婪的。它们会尽可能扩充符合范围,并且仅在必须时才回退以符合正规表达式的其余部分。正规表达式 <.+> 在 This is a <EM>first</EM> test 中符合 <EM>first</EM>。

在量词后加上问号,使其变为非贪婪模式。 <.+?> 在上述字符串中会比对出 <EM>。

更好的解法是遵循我的建议,尽量少用点号。使用 <[^<>]+> 可以快速比对 HTML 标签,而不用考虑属性。否定字符类别比点号更具体,这有助于 regex 引擎快速找到比对结果。

深入了解贪婪和非贪婪量词

群组和截取

在多个标记周围加上括号,将它们群组在一起。然后可以对群组套用量词。例如:Set(Value)? 会比对出 Set 或 SetValue。

括号会创建一个捕获组。上述范例有一个群组。在比对之后,如果比对到 Set,群组编号一不会包含任何内容。如果比对到 SetValue,群组编号一会包含 Value。如何访问群组的内容取决于您使用的软件或编程语言。群组编号零永远包含整个 regex 比对结果。

使用特殊语法 Set(?:Value)? 来群组标记,而不创建捕获组。如果您不打算使用群组的内容,这样会更有效率。不要将非捕获组语法中的问号与量词混淆。

深入了解群组和截取

反向引用

在正则表达式中,您可以使用反向引用 \1 来比对与捕获组比对到的相同文本。 ([abc])=\1 会比对出 a=a、b=b 和 c=c。它不会比对出任何其他内容。如果您的 regex 有多个捕获组,它们会从左到右依据其打开括号的顺序编号。

深入了解反向引用

命名组和反向引用

如果您的正则表达式有许多群组,追踪其数字可能会很麻烦。通过命名您的群组,让您的正则表达式更易于阅读。(?<mygroup>[abc])=\k<mygroup> 与 ([abc])=\1 相同,但您可以通过其名称来参考群组。

进一步了解命名组

Unicode 属性

\p{L} 符合给定 Unicode 类别中的单一字符。L 代表字母。\P{L} 符合不在给定 Unicode 类别中的单一字符。您可以在教程中找到 Unicode 类别的完整清单。

进一步了解 Unicode 正则表达式

环顾

环顾是一种特殊类型的群组。群组内的代码会正常配对,但正则表达式引擎会让群组放弃其配对,并仅保留结果。环顾会配对位置,就像锚点一样。它不会扩充正则表达式配对。

q(?=u) 会配对 q 在 question 中,但不会在 Iraq 中配对。这是正向环顾。 u 不是整体正则表达式配对的一部分。环顾会在字符串中 u 前的每个位置配对。

q(?!u) 会配对 q 在 Iraq 中,但不会在 question 中配对。这是负向环顾。环顾内的代码会尝试配对,其配对会被舍弃,而结果会被反转。

若要向后环顾,请使用后向环顾。正向后向环顾 (?<=a)b 会配对 b 在 abc 中。负向后向环顾 (?<!a)b 无法配对 abc。

您可以在环顾内使用完整的正则表达式。大多数应用程序仅允许在后向环顾中使用固定长度的表达式。

进一步了解环顾

自由间距语法

许多应用程序都有选项,标签可能是「自由间距」或「忽略空白」或「注解」,这会让正则表达式引擎忽略未转义的空白和换行符号,并让 # 字符开始注解,直到该行结束。这允许您使用空白来格式化您的正则表达式,让人类更容易阅读,因此也更容易维护。

深入了解自由间距

正規表示式快速入門
  • 简
  • 繁
  • En
關於正規表示式 » 正規表示式快速入門

歡迎
簡介
正規表示式快速入門
正規表示式教學
替換字串教學
應用程式和語言
正規表示式範例
正規表示式參考
替換字串參考

正規表示式快速入門

這個快速入門可讓您快速了解正規表示式。顯然地,這個簡短的簡介無法解釋正規表示式的全部內容。如需詳細資訊,請參閱正規表示式教學。快速入門中的每個主題都對應教學中的某個主題,因此您可以輕鬆地在兩者之間來回切換。

許多應用程式和程式語言都有自己的正規表示式實作,通常與其他實作略有不同,有時甚至有顯著差異。當兩個應用程式使用不同的正規表示式實作時,我們會說它們使用不同的「正規表示式風格」。這個快速入門說明了最受歡迎的正規表示式風格所支援的語法。

文字模式和比對

正規表示式,簡稱 regex,是一種描述一定量文字的模式。在此網站上,正規表示式會以灰色陰影顯示為 regex。這實際上是一個完全有效的 regex。這是最基本的模式,僅比對文字 regex。比對會在此網站上以藍色突顯。我們使用「字串」一詞來表示套用正規表示式的文字。字串會以 綠色 突顯。

在正規表示式中具有特殊意義的字元會以各種不同的顏色突顯。regex (?x)([Rr]egexp?)\? 以紫色顯示元標記,以綠色顯示群組,以橘色顯示字元類別,以藍色顯示量詞和其他特殊標記,並以灰色顯示跳脫字元。

文字字元

最基本的正規表示式包含一個單一的文字字元,例如 a。它會比對字串中該字元的第一次出現。如果字串是 Jack is a boy,它會比對 J 之後的 a。

這個正規表示法也可以匹配第二個 a。它只會在您告訴正規表示法引擎在第一次匹配後開始搜尋字串時執行此操作。在文字編輯器中,您可以使用其「尋找下一個」或「向前搜尋」功能來執行此操作。在程式語言中,通常有一個獨立的功能,您可以呼叫它來在先前的匹配後繼續搜尋字串。

十二個字元在正規表示法中具有特殊意義:反斜線 \、插入符號 ^、美元符號 $、句點或圓點 .、垂直線或管道符號 |、問號 ?、星號或星形 *、加號 +、開啟括弧 (、關閉括弧 )、開啟方括弧 [ 和開啟大括弧 {。這些特殊字元通常稱為「元字元」。大多數單獨使用時會產生錯誤。

如果您想在正規表示法中將任何這些字元用作文字,您需要使用反斜線跳脫它們。如果您想匹配 1+1=2,正確的正規表示法是 1\+1=2。否則,加號具有特殊意義。

深入瞭解文字字元

不可列印字元

您可以使用特殊字元序列將不可列印字元放入您的正規表示法中。使用 \t 來匹配一個標籤字元(ASCII 0x09),\r 來匹配回車(0x0D)和 \n 來匹配換行(0x0A)。更特別的不可列印字元有 \a(鈴聲,0x07),\e(跳脫,0x1B),\f(換頁,0x0C)和 \v(垂直標籤,0x0B)。請記住,Windows 文字檔案使用 \r\n 來終止列,而 UNIX 文字檔案使用 \n。

如果您的應用程式支援 Unicode,請使用 \uFFFF 或 \x{FFFF} 來插入一個 Unicode 字元。 \u20AC 或 \x{20AC} 匹配歐元貨幣符號。

如果您的應用程式不支援 Unicode,請使用 \xFF 來透過字元集中的十六進位索引來匹配一個特定字元。 \xA9 在 Latin-1 字元集中匹配版權符號。

所有不可列印字元都可直接用於正規表示式中,或作為字元類別的一部分。

進一步瞭解不可列印字元

字元類別或字元集

「字元類別」只會比對幾個字元中的其中一個。若要比對 a 或 e,請使用 [ae]。您可以在 gr[ae]y 中使用此方法來比對 gray 或 grey。字元類別只會比對單一字元。gr[ae]y 不會比對 graay、graey 或任何類似字串。字元類別中字元的順序並不重要。

您可以在字元類別中使用連字號來指定字元範圍。[0-9] 會比對 0 到 9 之間的單一數字。您可以使用多個範圍。[0-9a-fA-F] 會比對單一十六進位數字,不分大小寫。您可以結合範圍和單一字元。[0-9a-fxA-FX] 會比對十六進位數字或字母 X。

在開啟方括號後輸入插入符號會否定字元類別。結果是字元類別會比對不在字元類別中的任何字元。q[^x] 會在 question 中比對 qu。它不會比對 Iraq,因為在 q 之後沒有字元供否定的字元類別比對。

進一步瞭解字元類別

簡寫字元類別

\d 會比對單一數字字元,\w 會比對「字元字元」(字母數字字元加上底線),而 \s 會比對空白字元(包括標籤和換行符號)。簡寫實際比對的字元取決於您使用的軟體。在現代應用程式中,它們包含非英文字母和數字。

深入了解簡寫字元類別

點號匹配(幾乎)任何字元

點號匹配單一字元,換行字元除外。大多數應用程式都有「點號匹配所有」或「單行」模式,讓點號匹配任何單一字元,包括換行字元。

gr.y 匹配 gray、grey、gr%y 等。請謹慎使用點號。通常,字元類別或否定字元類別速度更快、更精確。

深入了解點號

錨點

錨點不匹配任何字元。它們匹配位置。 ^ 匹配字串開頭,$ 匹配字串結尾。大多數正規表示式引擎都有「多行」模式,讓 ^ 在任何換行後匹配,$ 在任何換行前匹配。例如,^b 僅匹配 bob 中的第一個 b。

\b 匹配字詞邊界。字詞邊界是 \w 可以匹配的字元與 \w 無法匹配的字元之間的位置。如果字串的第一個和/或最後一個字元是字詞字元,\b 也會在字串開頭和/或結尾匹配。 \B 匹配 \b 無法匹配的每個位置。

深入了解錨點

交替

交替是正規表示式中「或」的等效項。 cat|dog 在 About cats and dogs 中匹配 cat。如果再次套用正規表示式,它會匹配 dog。您可以新增任意數量的選項:cat|dog|mouse|fish。

交替具有所有正規運算符中最低的優先順序。cat|dog food 符合 cat 或 dog food。若要建立符合 cat food 或 dog food 的正規運算式,您需要將交替選項分組:(cat|dog) food。

深入了解交替

重複

問號使正規運算式中的前一個代幣成為選用。 colou?r 符合 colour 或 color。

星號或星號告訴引擎嘗試將前一個代幣符合零次或多次。加號告訴引擎嘗試將前一個代幣符合一次或多次。<[A-Za-z][A-Za-z0-9]*> 符合沒有任何屬性的 HTML 標籤。<[A-Za-z0-9]+> 較容易撰寫,但會符合無效的標籤,例如 <1>。

使用大括號指定特定的重複次數。使用 \b[1-9][0-9]{3}\b 來符合介於 1000 至 9999 之間的數字。\b[1-9][0-9]{2,4}\b 符合介於 100 至 99999 之間的數字。

深入了解量詞

貪婪和懶惰重複

重複運算符或量詞是貪婪的。它們會盡可能擴充符合範圍,並且僅在必須時才回退以符合正規運算式的其餘部分。正規運算式 <.+> 在 This is a <EM>first</EM> test 中符合 <EM>first</EM>。

在量詞後加上問號,使其變為非貪婪模式。 <.+?> 在上述字串中會比對出 <EM>。

更好的解法是遵循我的建議,盡量少用點號。使用 <[^<>]+> 可以快速比對 HTML 標籤,而不用考慮屬性。否定字元類別比點號更具體,這有助於 regex 引擎快速找到比對結果。

深入了解貪婪和非貪婪量詞

群組和擷取

在多個標記周圍加上括號,將它們群組在一起。然後可以對群組套用量詞。例如:Set(Value)? 會比對出 Set 或 SetValue。

括號會建立一個擷取群組。上述範例有一個群組。在比對之後,如果比對到 Set,群組編號一不會包含任何內容。如果比對到 SetValue,群組編號一會包含 Value。如何存取群組的內容取決於您使用的軟體或程式語言。群組編號零永遠包含整個 regex 比對結果。

使用特殊語法 Set(?:Value)? 來群組標記,而不建立擷取群組。如果您不打算使用群組的內容,這樣會更有效率。不要將非擷取群組語法中的問號與量詞混淆。

深入了解群組和擷取

反向參照

在正規表示式中,您可以使用反向參照 \1 來比對與擷取群組比對到的相同文字。 ([abc])=\1 會比對出 a=a、b=b 和 c=c。它不會比對出任何其他內容。如果您的 regex 有多個擷取群組,它們會從左到右依據其開啟括號的順序編號。

深入了解反向參照

命名群組和反向參照

如果您的正規表示式有許多群組,追蹤其數字可能會很麻煩。透過命名您的群組,讓您的正規表示式更易於閱讀。(?<mygroup>[abc])=\k<mygroup> 與 ([abc])=\1 相同,但您可以透過其名稱來參考群組。

進一步了解命名群組

Unicode 屬性

\p{L} 符合給定 Unicode 類別中的單一字元。L 代表字母。\P{L} 符合不在給定 Unicode 類別中的單一字元。您可以在教學課程中找到 Unicode 類別的完整清單。

進一步了解 Unicode 正規表示式

環顧

環顧是一種特殊類型的群組。群組內的代碼會正常配對,但正規表示式引擎會讓群組放棄其配對,並僅保留結果。環顧會配對位置,就像錨點一樣。它不會擴充正規表示式配對。

q(?=u) 會配對 q 在 question 中,但不會在 Iraq 中配對。這是正向環顧。 u 不是整體正規表示式配對的一部分。環顧會在字串中 u 前的每個位置配對。

q(?!u) 會配對 q 在 Iraq 中,但不會在 question 中配對。這是負向環顧。環顧內的代碼會嘗試配對,其配對會被捨棄,而結果會被反轉。

若要向後環顧,請使用後向環顧。正向後向環顧 (?<=a)b 會配對 b 在 abc 中。負向後向環顧 (?<!a)b 無法配對 abc。

您可以在環顧內使用完整的正規表示式。大多數應用程式僅允許在後向環顧中使用固定長度的表示式。

進一步了解環顧

自由間距語法

許多應用程式都有選項,標籤可能是「自由間距」或「忽略空白」或「註解」,這會讓正規表示式引擎忽略未跳脫的空白和換行符號,並讓 # 字元開始註解,直到該行結束。這允許您使用空白來格式化您的正規表示式,讓人類更容易閱讀,因此也更容易維護。

深入了解自由間距

Regular Expressions Quick Start
  • 简
  • 繁
  • En
About Regular Expressions » Regular Expressions Quick Start

Welcome
Introduction
Regular Expressions Quick Start
Regular Expressions Tutorial
Replacement Strings Tutorial
Applications and Languages
Regular Expressions Examples
Regular Expressions Reference
Replacement Strings Reference

Regular Expressions Quick Start

This quick start gets you up to speed quickly with regular expressions. Obviously, this brief introduction cannot explain everything there is to know about regular expressions. For detailed information, consult the regular expressions tutorial. Each topic in the quick start corresponds with a topic in the tutorial, so you can easily go back and forth between the two.

Many applications and programming languages have their own implementation of regular expressions, often with slight and sometimes with significant differences from other implementations. When two applications use a different implementation of regular expressions, we say that they use different “regular expression flavors”. This quick start explains the syntax supported by the most popular regular expression flavors.

Text Patterns and Matches

A regular expression, or regex for short, is a pattern describing a certain amount of text. On this website, regular expressions are shaded gray as regex. This is actually a perfectly valid regex. It is the most basic pattern, simply matching the literal text regex. Matches are highlighted in blue on this site. We use the term “string” to indicate the text that the regular expression is applied to. Strings are highlighted in green.

Characters with special meanings in regular expressions are highlighted in various different colors. The regex (?x)([Rr]egexp?)\? shows meta tokens in purple, grouping in green, character classes in orange, quantifiers and other special tokens in blue, and escaped characters in gray.

Literal Characters

The most basic regular expression consists of a single literal character, such as a. It matches the first occurrence of that character in the string. If the string is Jack is a boy, it matches the a after the J.

This regex can match the second a too. It only does so when you tell the regex engine to start searching through the string after the first match. In a text editor, you can do so by using its “Find Next” or “Search Forward” function. In a programming language, there is usually a separate function that you can call to continue searching through the string after the previous match.

Twelve characters have special meanings in regular expressions: the backslash \, the caret ^, the dollar sign $, the period or dot ., the vertical bar or pipe symbol |, the question mark ?, the asterisk or star *, the plus sign +, the opening parenthesis (, the closing parenthesis ), the opening square bracket [, and the opening curly brace {. These special characters are often called “metacharacters”. Most of them are errors when used alone.

If you want to use any of these characters as a literal in a regex, you need to escape them with a backslash. If you want to match 1+1=2, the correct regex is 1\+1=2. Otherwise, the plus sign has a special meaning.

Learn more about literal characters

Non-Printable Characters

You can use special character sequences to put non-printable characters in your regular expression. Use \t to match a tab character (ASCII 0x09), \r for carriage return (0x0D) and \n for line feed (0x0A). More exotic non-printables are \a (bell, 0x07), \e (escape, 0x1B), \f (form feed, 0x0C) and \v (vertical tab, 0x0B). Remember that Windows text files use \r\n to terminate lines, while UNIX text files use \n.

If your application supports Unicode, use \uFFFF or \x{FFFF} to insert a Unicode character. \u20AC or \x{20AC} matches the euro currency sign.

If your application does not support Unicode, use \xFF to match a specific character by its hexadecimal index in the character set. \xA9 matches the copyright symbol in the Latin-1 character set.

All non-printable characters can be used directly in the regular expression, or as part of a character class.

Learn more about non-printable characters

Character Classes or Character Sets

A “character class” matches only one out of several characters. To match an a or an e, use [ae]. You could use this in gr[ae]y to match either gray or grey. A character class matches only a single character. gr[ae]y does not match graay, graey or any such thing. The order of the characters inside a character class does not matter.

You can use a hyphen inside a character class to specify a range of characters. [0-9] matches a single digit between 0 and 9. You can use more than one range. [0-9a-fA-F] matches a single hexadecimal digit, case insensitively. You can combine ranges and single characters. [0-9a-fxA-FX] matches a hexadecimal digit or the letter X.

Typing a caret after the opening square bracket negates the character class. The result is that the character class matches any character that is not in the character class. q[^x] matches qu in question. It does not match Iraq since there is no character after the q for the negated character class to match.

Learn more about character classes

Shorthand Character Classes

\d matches a single character that is a digit, \w matches a “word character” (alphanumeric characters plus underscore), and \s matches a whitespace character (includes tabs and line breaks). The actual characters matched by the shorthands depends on the software you’re using. In modern applications, they include non-English letters and numbers.

Learn more about shorthand character classes

The Dot Matches (Almost) Any Character

The dot matches a single character, except line break characters. Most applications have a “dot matches all” or “single line” mode that makes the dot match any single character, including line breaks.

gr.y matches gray, grey, gr%y, etc. Use the dot sparingly. Often, a character class or negated character class is faster and more precise.

Learn more about the dot

Anchors

Anchors do not match any characters. They match a position. ^ matches at the start of the string, and $ matches at the end of the string. Most regex engines have a “multi-line” mode that makes ^ match after any line break, and $ before any line break. E.g. ^b matches only the first b in bob.

\b matches at a word boundary. A word boundary is a position between a character that can be matched by \w and a character that cannot be matched by \w. \b also matches at the start and/or end of the string if the first and/or last characters in the string are word characters. \B matches at every position where \b cannot match.

Learn more about anchors

Alternation

Alternation is the regular expression equivalent of “or”. cat|dog matches cat in About cats and dogs. If the regex is applied again, it matches dog. You can add as many alternatives as you want: cat|dog|mouse|fish.

Alternation has the lowest precedence of all regex operators. cat|dog food matches cat or dog food. To create a regex that matches cat food or dog food, you need to group the alternatives: (cat|dog) food.

Learn more about alternation

Repetition

The question mark makes the preceding token in the regular expression optional. colou?r matches colour or color.

The asterisk or star tells the engine to attempt to match the preceding token zero or more times. The plus tells the engine to attempt to match the preceding token once or more. <[A-Za-z][A-Za-z0-9]*> matches an HTML tag without any attributes. <[A-Za-z0-9]+> is easier to write but matches invalid tags such as <1>.

Use curly braces to specify a specific amount of repetition. Use \b[1-9][0-9]{3}\b to match a number between 1000 and 9999. \b[1-9][0-9]{2,4}\b matches a number between 100 and 99999.

Learn more about quantifiers

Greedy and Lazy Repetition

The repetition operators or quantifiers are greedy. They expand the match as far as they can, and only give back if they must to satisfy the remainder of the regex. The regex <.+> matches <EM>first</EM> in This is a <EM>first</EM> test.

Place a question mark after the quantifier to make it lazy. <.+?> matches <EM> in the above string.

A better solution is to follow my advice to use the dot sparingly. Use <[^<>]+> to quickly match an HTML tag without regard to attributes. The negated character class is more specific than the dot, which helps the regex engine find matches quickly.

Learn more about greedy and lazy quantifiers

Grouping and Capturing

Place parentheses around multiple tokens to group them together. You can then apply a quantifier to the group. E.g. Set(Value)? matches Set or SetValue.

Parentheses create a capturing group. The above example has one group. After the match, group number one contains nothing if Set was matched. It contains Value if SetValue was matched. How to access the group’s contents depends on the software or programming language you’re using. Group zero always contains the entire regex match.

Use the special syntax Set(?:Value)? to group tokens without creating a capturing group. This is more efficient if you don’t plan to use the group’s contents. Do not confuse the question mark in the non-capturing group syntax with the quantifier.

Learn more about grouping and capturing

Backreferences

Within the regular expression, you can use the backreference \1 to match the same text that was matched by the capturing group. ([abc])=\1 matches a=a, b=b, and c=c. It does not match anything else. If your regex has multiple capturing groups, they are numbered counting their opening parentheses from left to right.

Learn more about backreferences

Named Groups and Backreferences

If your regex has many groups, keeping track of their numbers can get cumbersome. Make your regexes easier to read by naming your groups. (?<mygroup>[abc])=\k<mygroup> is identical to ([abc])=\1, except that you can refer to the group by its name.

Learn more about named groups

Unicode Properties

\p{L} matches a single character that is in the given Unicode category. L stands for letter. \P{L} matches a single character that is not in the given Unicode category. You can find a complete list of Unicode categories in the tutorial.

Learn more about Unicode regular expressions

Lookaround

Lookaround is a special kind of group. The tokens inside the group are matched normally, but then the regex engine makes the group give up its match and keeps only the result. Lookaround matches a position, just like anchors. It does not expand the regex match.

q(?=u) matches the q in question, but not in Iraq. This is positive lookahead. The u is not part of the overall regex match. The lookahead matches at each position in the string before a u.

q(?!u) matches q in Iraq but not in question. This is negative lookahead. The tokens inside the lookahead are attempted, their match is discarded, and the result is inverted.

To look backwards, use lookbehind. The positive lookbehind (?<=a)b matches the b in abc. The negative lookbehind (?<!a)b fails to match abc.

You can use a full-fledged regular expression inside lookahead. Most applications only allow fixed-length expressions in lookbehind.

Learn more about lookaround

Free-Spacing Syntax

Many application have an option that may be labeled “free-spacing” or “ignore whitespace” or “comments” that makes the regular expression engine ignore unescaped spaces and line breaks and that makes the # character start a comment that runs until the end of the line. This allows you to use whitespace to format your regular expression in a way that makes it easier for humans to read and thus makes it easier to maintain.

Learn more about free-spacing

©2015-2025 艾丽卡 support@alaica.com