如何合并VS Code代码片段实现替换不同前导空格为星号
问题
我有两个VS Code代码片段,分别能把非空行的前导4个空格替换为*、前导8个空格替换为**。现在想把它们合并成一个代码片段,实现:行首有4个空格就替换为单个*,有8个空格就替换为双**,示例输入输出如下,该怎么实现?
现有代码片段
"Replace leading 4 spaces of non-empty lines with *": { "body": [ "${TM_SELECTED_TEXT/^([ ]{4})(.+)$/* $2/gm}" ], "description": "Replace leading 4 spaces of non-empty lines with *" }, "Replace leading 8 spaces of non-empty lines with **": { "body": [ "${TM_SELECTED_TEXT/^([ ]{8})(.+)$/** $2/gm}" ], "description": "Replace leading 8 spaces of non-empty lines with **" },
示例输入
Motivation's First Law (Law of Persistence): A person will remain in their current state of motivation In simpler terms, individuals tend to maintain their current Motivation's Second Law (Law of Momentum): The rate of change of motivation of a person is In simpler terms, this law suggests that the greater
示例输出
* Motivation's First Law (Law of Persistence): ** A person will remain in their current state of motivation ** In simpler terms, individuals tend to maintain their current * Motivation's Second Law (Law of Momentum): ** The rate of change of motivation of a person is ** In simpler terms, this law suggests that the greater
解决方案
可以利用VS Code代码片段的正则分支匹配和条件替换,实现一次处理两种前导空格的需求,合并后的代码片段如下:
"Replace leading 4/8 spaces with * or **": { "body": [ "${TM_SELECTED_TEXT/^([ ]{8})(.+)$|^([ ]{4})(.+)$/${1:+** }${2:+$2}${3:+* }${4:+$4}/gm}" ], "description": "Replace leading 8 spaces with **, leading 4 spaces with * for non-empty lines" }
逻辑说明
- 正则规则
^([ ]{8})(.+)$|^([ ]{4})(.+)$:用|划分两个匹配分支,优先匹配8个空格的行(避免4空格规则提前匹配掉8空格的前4个字符),再匹配4个空格的行,两个分支分别捕获空格和后续内容。 - 替换规则
${1:+** }${2:+$2}${3:+* }${4:+$4}:${1:+** }:如果第一个分组(8个空格)匹配成功,替换为**${2:+$2}:保留8个空格后的文本内容${3:+* }:如果第三个分组(4个空格)匹配成功,替换为*${4:+$4}:保留4个空格后的文本内容
这样就能在一次替换中同时处理两种场景,达到预期效果。
内容的提问来源于stack exchange,提问作者Ahmad Ismail
相关产品推荐
相关产品推荐

