Reputation: 1123
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
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 boundaryid="
- 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:
Upvotes: 1