anegru
anegru

Reputation: 1123

How to replace all whitespace between quotes that start with specific string with underscore in VSCode?

I have the following string:

this is a sample id="aaa bbb ccc" name="abc abc"

I want to match only the whitespace between quotes that start with the string "id=" and replace all occurrences with underscore. The result string should look like:

this is a sample id="aaa_bbb_ccc" name="abc abc"

The following regex matches all whitespace between quotes, but it doesn't take into account the fact that the quotes must be preceded by "id="

\s(?=[^"]*"[^"]*(?:"[^"]*"[^"]*)*$)

Quotes inside quotes are not possible.

Upvotes: 0

Views: 776

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627082

Since starting with VS Code 1.31, infinite-width lookbehinds are supported, you may use

(?<=\bid="[^"]*?)\s

Or, to make sure there actually is a " after the whitespace,

(?<=\bid="[^"]*?)\s(?=[^"]*")

Replace with _.

See the regex demo online. Details:

  • (?<=\bid="[^"]*?) - a positive lookbehind that matches a location that is immediately preceded with
    • \b - word boundary
    • id=" - a literal id=" string
    • [^"]*? - any 0 or more chars other than ", as few as possible (due to *? non-greedy quantifier)
  • \s - a whitespace
  • (?=[^"]*") - a positive lookahead that matches a location immediately followed with any 0+ chars other than " (with [^"]* pattern) and then a ".

See the proof it works in VSCode:

enter image description here

Upvotes: 1

Related Questions