正则表达式 Return 发现组 IF 字符串不以 ' - VSCode - Search/Replace 开头

RegEx Return found Group IF String Does NOT start with ' - VSCode - Search/Replace

所以,我做了一个全局可撤销的 RegEx 搜索和替换。我忘了在替换中包含 '。现在我需要搜索与以下匹配的字符串。它不能以 ' 开头,结尾必须有 | translate。这些是 Angular 翻译键 - 它们可以遍布在模板文件中 (HTML)。他们总是以 {{ 开头,有 |翻译,并以}}结尾。现在更重要的是他们可能有间距或换行问题(不太可能但有机会)。所以它可能是 {{_ _ textToKeepAdd'To _ _ | _ _ 翻译 _ _ }} _ _ 是空格或换行的可能性。

要匹配的字符串(无开头 '):

anyText' | translate

<other text or tags>{{ anyText' | translate

{{  // line break
anyText' | translate

anyText'
 | translate // line break

不匹配的字符串:

'anyText' | translate

 <other text or tags>{{ 'anyText' | translate

'anyText'
 | translate

Return 字符串格式:

'anyText' | translate

示例:

blahadskfjlksjdf' | translate = 'blahadskfjlksjdf' | translate

'SkipMe' | translate = not found for replacement bc it starts with a '.

And <other text or tags>{{ anyText' | translate =  <other text or tags>{{ 'anyText' | translate

这是我比较喜欢的代码 - '(?:\w+\.){1,3}(?=\w+'\s+\|\s+translate\b)

我需要一组 capturing/returning 来替换。

这应该可以解决问题:

替换 \{\{(?:\s|\n)*(?!(?:'|\s|\n))(.*')(?:\s|\n)*(\|(?:\s|\n)+translate)\b

{{ '

Regex 101 Demo

解释:

  • \{\{ - 匹配两个左大括号

  • (?:\s|\n)* - 匹配任意数量的空白字符

  • (?!(?:'|\s|\n))(.*') - 捕获组 1;匹配任何非 ' 字符后跟单个 '

  • 的连续字符串
  • (?:\s|\n)* - 匹配任意数量的空白字符

  • (\|(?:\s|\n)+translate) - 捕获组 2;匹配 | 后跟至少一个或多个空白字符,然后是单词 translate.

  • \b - 匹配单词边界

我建议使用

查找内容\{\{[\s\n]*(?!['\s\n])(.*')[\s\n]*(\|[\s\n]+translate)\b
替换为{{ '

参见 online regex demo(已更改以反映其在 VSCode 中的工作方式)。

详情

  • ^ - 行首
  • \{\{ - {{ 子串
  • [\s\n]* - 0+ whitespaces/linebreaks
  • (?!['\s\n]) - 如果在当前位置的右侧立即有一个 ' 或一个白色的 space(包括换行符)[=54=,则否定前瞻会导致匹配失败]
  • (.*') - 捕获第 1 组:除换行字符外的任何 0+ 个字符,尽可能多,然后是 ' 字符
  • [\s\n]* - 0+ whitespaces/linebreaks
  • (\|[\s\n]+translate)\b - 第 2 组:一个 |、1+ whitespaces/linebreaks 和一个完整的单词 translate.

替换为'、第1组反向引用(指第1组捕获的值)、space和第2组反向引用(指第2组捕获的值)。