跟我學正規表示式 8 使用後向引用

2021-06-26 23:29:24 字數 1892 閱讀 9313

前一章中介紹了如何使用子表示式將字元分成組。這種分組的主要用途之一是可以控制組的重複次數(在前一章中已經演示過)。本章中將介紹子表示式乙個更重要的用法——使用後向引用。

理解後向引用

理解後向引用需求的最好辦法是看乙個例子。

html

開發者經常使用段落標籤(

content is divided into two sections:

information about macromedia coldfusion.

information about bluetooth, 802.11, and more.

正規表示式

<[hh]1>.*結果

content is divided into two sections:

information about macromedia coldfusion.

information about bluetooth, 802.11, and more.

分析這裡的模式「<[hh]1>.*」匹配了第乙個段落(從

),同樣可以匹配

content is divided into two sections:

information about macromedia coldfusion.

information about bluetooth, 802.11, and more.

正規表示式

<[hh][1-6]>.*?結果

content is divided into two sections:

information about macromedia coldfusion.

information about bluetooth, 802.11, and more.

分析這看起來可以工作:「<[hh][1-6]>」可以匹配任何開始的段落標籤(在例子中包括

content is divided into two sections:

information about macromedia coldfusion.

information about bluetooth, 802.11, and more.

information about macromedia coldfusion.

information about bluetooth, 802.11, and more.

information about macromedia coldfusion.

information about bluetooth, 802.11, and more.

information about macromedia coldfusion.

information about bluetooth, 802.11, and more.

information about macromedia coldfusion.

information about bluetooth, 802.11, and more.

information about macromedia coldfusion.

information about bluetooth, 802.11, and more.

this is not valid html

分析此模式「(<[hh]1>)(.*?)()」將段落標籤內容分解成三個部分:開始標籤、文字和結束標籤。第二個模式中將這些內容放在了一起:

$1包含了開始標籤,「 \u$2\e」轉換了第二個子表示式到其大寫形式,

$3中包含了結束標籤。

小結子表示式用來定義了一組字元。除了可以用來進行重複匹配以外(在前一章中已經演示過),子表示式還可以用來引用。這種引用被稱為後向引用(非常遺憾的是,後向引用的語法並不相同)後向引用在文字匹配和替換操作中都很有用。

亦歌亦行

@

跟我學正規表示式 8 使用後向引用

前一章中介紹了如何使用子表示式將字元分成組。這種分組的主要用途之一是可以控制組的重複次數 在前一章中已經演示過 本章中將介紹子表示式乙個更重要的用法 使用後向引用。理解後向引用 理解後向引用需求的最好辦法是看乙個例子。html 開發者經常使用段落標籤 content is divided into ...

正規表示式 後向引用

使用小括號指定乙個子表示式後,匹配這個子表示式的文字 也就是此分組捕獲的內容 可以在表示式或其它程式中作進一步的處理。預設情況下,每個分組會自動擁有乙個組號,規則是 從左向右,以分組的左括號為標誌,第乙個出現的分組的組號為1,第二個為2,以此類推。後向引用用於重複搜尋前面某個分組匹配的文字。例如,1...

正規表示式 後向引用

使用小括號指定乙個子表示式後,匹配這個子表示式的文字 也就是此分組捕獲的內容 可以在表示式或其它程式中作進一步的處理。預設情況下,每個分組會自動擁有乙個組號,規則是 從左向右,以分組的左括號為標誌,第乙個出現的分組的組號為1,第二個為2,以此類推。分組0對應整個正規表示式 實際上組號分配過程是要從左...