Notepad++ 正则表达式查找替换括号内的空格

3
在Notepad++中,想要更改如下内容:
    [City tier] [nvarchar](max) NULL,
    [Counting unit] [nvarchar](max) NULL,

变成这样:

    [City_tier] [nvarchar](max) NULL,
    [Counting_unit] [nvarchar](max) NULL,

我使用 [\w+(\s)\w+] 定位了这两个记录,但是当我使用 \1_ 进行替换时,出现了问题。

     _ [nvarchar](max) NULL,
     _ [nvarchar](max) NULL,
2个回答

5

您可以使用此PCRE正则表达式进行搜索:

((?:\[|(?!^)\G)[^]\s]*)\s

并替换为:

$1_

正则表达式演示

正则表达式详情:

  • (:开始捕获组#1
    • (?::开始非捕获组
      • \[:匹配一个 [
      • |:或者
      • (?!^)\G:从上一个匹配的结尾再次开始匹配
    • ):结束非捕获组
    • [^]\s]*:匹配0个或多个不是空格和]的任意字符
  • ):结束捕获组#1
  • \s:匹配一个空格

我们能不能只用 ((?:\[)[^]\s]*)\s 来实现呢?演示 - Arvind Kumar Avinash
实际上,如果在 [...] 中有多个空格,例如 [City main tier],那么这种方法是行不通的。 - anubhava

1
Notepad++支持使用\G\K,这可以让你更好地使用编程。
(?:\G(?!\A)|\[)[^][\s]+\K\s+

这里需要被下划线替换,详见regex101.com上的演示


这句话的意思是:“这可以归纳为”。
(?:           # non-capturing group (?:...)
    \G(?!\A)  # match after the last match but not at the very start
    |         # or
    \[        # a "[" literally
 )           
 [^][\s]+\K   # not "]" nor "[" nor spaces, \K -> "forget everything on the left"
 \s+          # whitespace characters

实际上,此结构仅匹配方括号内的空格。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接