Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all whitespace EXCEPT what is contained in the capture group

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...

like image 769
SnareChops Avatar asked Oct 30 '22 14:10

SnareChops


1 Answers

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.

like image 107
Tim Pietzcker Avatar answered Nov 12 '22 17:11

Tim Pietzcker