如何在捕获组内进行替换 [英] How to replace within a capture group

查看:44
本文介绍了如何在捕获组内进行替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在修改现有的 HTML 文档.我正在做一些事情,比如添加目录等.

I am modifying an existing HTML doc. I'm doing things like adding a table of contents etc.

我有一个带有此 ID 的标题:id="超越智力限制"(真的!)

I have a heading with this ID: id="transcending intellectual limitations" (for real!)

我希望能够找到整个 ID,然后用连字符替换空格.

I want to be able to find the whole ID, and then replace the spaces with hyphens.

如果我只有 ID 会很简单,但我不想删除整个文档中的所有空格.

It would be simple if I had just the IDs but I don't want to remove all the spaces in the whole document.

我对正则表达式相当陌生,我正在使用 Sublime 的查找和替换来执行此操作.

I'm reasonably new to regex, I'm using Sublime's find and replace to do this.

推荐答案

可以使用

(?:\bid="|(?!^)\G)[^\s"]*\K\s+ 

并替换为您需要替换空格的任何内容.

And replace with anything you need to replace spaces with.

(?:\bid="|(?!^)\G) 模式设置初始边界:id=" 或最后一个的结尾成功的比赛.此模式提供了一个包含两个备选方案的备选列表.\b 匹配单词边界,以便 id=" 作为整个单词匹配.\G 运算符匹配字符串的开头并且在 ech 成功匹配之后.为了排除起始位置,添加了一个负的 (?!^) 前瞻(后面没有字符串起始位置)."你离开的地方:\G 断言".

The (?:\bid="|(?!^)\G) pattern sets the initial boundary: either id=" or the end of the last successful match. This pattern presents an alternation list with two alternatives. \b matches a word boundary so that id=" is matched as a whole word. The \G operator matches at the start of the string and after ech successful match. To exclude the start position, a negative (?!^) lookahead is added (not followed with a string start position). See more about \G in "Where You Left Off: The \G Assertion".

[^\s"]* 匹配除空格和引号之外的零个或多个字符.

The [^\s"]* matches zero or more characters other than whitespace and a quote.

\K 运算符使正则表达式引擎忽略匹配缓冲区中迄今为止匹配的所有文本.

The \K operator makes the regex engine omit all the text matched so far from the match buffer.

\s+ 最终匹配一个或多个将被替换的空格.

The \s+ finally matches one or more whitespaces that will be replaced.

Regex101 演示

这篇关于如何在捕获组内进行替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆