Regex Dialect: JavaScript
I have the following capture group (('|").*?[^\\\2]\2)
that selects a quoted string excluding escaped quotes.
Matches these for example...
"Felix's pet"
'Felix\'s pet'
However I would now like to remove all whitespace from a string except anything matching this pattern. Is there perhaps a way to back reference the capture group \1
and then exclude it from the matches?
I have attempted to do so with my limited RegEx knowledge, but so far it I can only select the space immediately preceding or following the pattern.
I have saved my test script on regexr for convenience if you would like to play around with my example.
Intended results:
key : string
becomes key:string
dragon : "Felix's pet"
becomes dragon:"Felix's pet"
"Hello World" something here "Another String"
becomes
"Hello World"somethinghere"Another String"
etc...
This is extremely hard to do with regular expressions. The following works:
result = subject.replace(/ (?=(?:(?:\\.|"(?:\\.|[^"\\])*"|[^\\'"])*'(?:\\.|"(?:\\.|[^"'\\])*"|[^\\'])*')*(?:\\.|"(?:\\.|[^"\\])*"|[^\\'])*$)(?=(?:(?:\\.|'(?:\\.|[^'\\])*'|[^\\'"])*"(?:\\.|'(?:\\.|[^'"\\])*'|[^\\"])*")*(?:\\.|'(?:\\.|[^'\\])*'|[^\\"])*$)/g, "");
I've built this answer from one of my earlier answers to a similar, but not identical question; therefore I'll refer you to it for an explanation.
You can test it live on regex101.com.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With