Search code examples
regexvisual-studio-codesublimetext3

Manipulate regex capture group in replacement in VSCode / Sublime


In my Javascript file, I want to replace:

var user1 = {id: 'Alan Banks'};
var user2 = {id: 'Chris Daily'};

with

var user1 = {id: 'Alan_Banks'};
var user2 = {id: 'Chris_Daily'};

I can match the user names with the following regex in VSCode, Sublime (and Dreamweaver too, out of desperation):

id: '(.*?)'

So capture group $1 now holds the content of the id property of each user.

How can I perform the second part of my operation, being replacing the spaces in the captured substring with underscores?


Solution

  • In Visual Studio Code, you can use

    Find: (?<=id:\s*'[^']*?)\s(?=[^']*')
    Replace: _

    See the regex demo. Details:

    • (?<=id:\s*'[^']*?) - a positive lookahead that matches a location that is immediately preceded with id:, 0+ whitespaces, ', and then any 0 or more chars other than ' as few as possible
    • \s - a whitespace
    • (?=[^']*') - a positive lookahead that matches a location that is immediately followed with 0+ chars other than ' and then '.

    In Sublime Text 3, that supports PCRE regex search and replace, you can use

    Find: (?:\G(?!\A)|id:\s*')[^'\s]*\K\s(?=[^']*')
    Replace: _

    See another regex demo. Details:

    • (?:\G(?!\A)|id:\s*') - end of the previous match or id:, 0+ whitespaces and '
    • [^'\s]* - 0+ chars other than ' and whitespace
    • \K - omits all text matched so far
    • \s - a whitespace
    • (?=[^']*') - a positive lookahead that matches a location that is immediately followed with 0+ chars other than ' and then '.