MonkeyHua

正则表达式九:反向引用匹配

介绍

同时搭配子表达式匹配,可提供强大的替换功能;

元字符列表

  • 反向引用匹配:\n$n
  • 大小写转换终止符:\E
  • 小写转换:\l
  • 批量小写转换:\L
  • 大写转换:\u
  • 批量大写转换:\U

反向引用匹配(\n$n

用于引用第n项子表达式,各个平台间格式有所差异

示例

原始内容:

<body>
<h1>Welcome to my Homepage</h1>
Content is divided into two sections:<br/>
<h2>SQL</h2>
Information about SQL.
<h2>RegEx</h2>
Information about Regular Expressions.
<h2>This is not valid HTML</h3>
</body>

正则表达式1:

<[hH][1-6]>.*?<\/[hH][1-6]>

<body>
<h1>Welcome to my Homepage</h1>
Content is divided into two sections:<br/>
<h2>SQL</h2>
Information about SQL.
<h2>RegEx</h2>
Information about Regular Expressions.
<h2>This is not valid HTML</h3>
</body>

说明:[hH][1-6]代表匹配html的h1-h6标题
.*?匹配标题内容,且为懒惰模式

正则表达式2:

<[hH]([1-6])>.*?<\/[hH]\1>

<body>
<h1>Welcome to my Homepage</h1>
Content is divided into two sections:<br/>
<h2>SQL</h2>
Information about SQL.
<h2>RegEx</h2>
Information about Regular Expressions.
<h2>This is not valid HTML</h3>
</body>

说明:([1-6])代表子表达式1
\1代表反向引用子表达式1,确保标签开头和结尾内容一致

替换操作(()$1\E\l\L\u\U

用于执行正则表达式替换操作

常规替换示例

原始内容:

313-555-1234
248-555-9999
810-555-9000

查找正则表达式:

(\d{3})(-)(\d{3})(-)(\d{4})

替换正则表达式:

($1) $3-$5

替换结果:

(313) 555-1234
(248) 555-9999
(810) 555-9000

说明:

  1. 从左至右依次分析查找正则表达式
  • (\d{3})代表子表达式1,匹配开头数字
  • (-)代表子表达式2
  • (\d{3})代表子表达式3,匹配中间数字
  • (-)代表子表达式4
  • (\d{4})代表子表达式5,匹配末尾数字
  1. 从左至右依次分析替换正则表达式
  • $1代表使用子表达式1的值
  • $3代表使用子表达式3的值
  • $5代表使用子表达式5的值

大小写转换替换示例

原始内容:

<body>
<h1>Welcome to my Homepage</h1>
Content is divided into two sections:<br/>
<h2>SQL</h2>
Information about SQL.
<h2>RegEx</h2>
Information about Regular Expressions.
<h2>This is not valid HTML</h3>
</body>

查找正则表达式:

(<[Hh]1>)(.*?)(<\/[Hh]1>)

替换正则表达式:

$1\U$2\E$3

替换结果:

<body>
<h1>WELCOME TO MY HOMEPAGE</h1>
Content is divided into two sections:<br/>
<h2>SQL</h2>
Information about SQL.
<h2>RegEx</h2>
Information about Regular Expressions.
<h2>This is not valid HTML</h3>
</body>

说明:

  1. 从左至右依次分析查找正则表达式
  • (<[Hh]1>)代表子表达式1,匹配标题1开始标签
  • (.*?)代表子表达式2,懒惰模式匹配标题1内容
  • (<\/[Hh]1>)代表子表达式3,匹配标题1结束标签
  1. 从左至右依次分析替换正则表达式
  • $1代表使用子表达式1的值
  • \U$2\E代表使用子表达式2的值,并且将所有内容转换成大写
  • $3代表使用子表达式3的值

posted on 2026-03-25 16:41  MonkeyHua  阅读(3)  评论(0)    收藏  举报

导航