notepad++ regex find and replace spaces between brackets

Viewed 511

In notepad++, want to change this:

    [City tier] [nvarchar](max) NULL,
    [Counting unit] [nvarchar](max) NULL,

to this:

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

I have used [\w+(\s)\w+] to locate these two records, but when i use \1_ in replace, i got

     _ [nvarchar](max) NULL,
     _ [nvarchar](max) NULL,
2 Answers

You may use this PCRE regex for search:

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

and replace with:

$1_

RegEx Demo

RegEx Details:

  • (: Start capture group #1
    • (?:: Start non-capture group
      • \[: Match a [
      • |: OR
      • (?!^)\G: Start matching again from end of the previous match
    • ): End non-capture group
    • [^]\s]*: Match 0 or more any characters that are not whitespace and not a ]
  • ): End capture group #1
  • \s: Match a whitespace

Notepad++ supports \G and \K which allows you to use

(?:\G(?!\A)|\[)[^][\s]+\K\s+

This needs to be replaced by an underscore, see a demo on regex101.com.


This boils down to

(?:           # 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

Effectively, this construct only matches whitespaces within square brackets.

Related