Delete all spaces EXCEPT what is in the capture group

Regex Dialog : JavaScript

I have the following capture group (('|").*?[^\\\2]\2) that selects a quoted string excluding escaped quotes.

Corresponds to these, for example ...

 "Felix pet" 'Felix\ pet' 

However, now I would like to remove all spaces from the line except corresponding to this pattern. Is there a way to return to capture group link \1 and then exclude it from matches?

I tried to do this with my limited knowledge of RegEx, but so far I can only select the space immediately preceding or following the pattern.

I saved my test script on regexr for convenience if you want to play around with my example.

Expected Results :

key : string becomes key:string

dragon : "Felix pet" becomes dragon:"Felix pet"

"Hello World" something here "Another String"

becomes

"Hello World"somethinghere"Another String"

etc...

+5
source share
2 answers

This is very difficult to do with regular expressions. The following works:

 result = subject.replace(/ (?=(?:(?:\\.|"(?:\\.|[^"\\])*"|[^\\'"])*'(?:\\.|"(?:\\.|[^"'\\])*"|[^\\'])*')*(?:\\.|"(?:\\.|[^"\\])*"|[^\\'])*$)(?=(?:(?:\\.|'(?:\\.|[^'\\])*'|[^\\'"])*"(?:\\.|'(?:\\.|[^'"\\])*'|[^\\"])*")*(?:\\.|'(?:\\.|[^'\\])*'|[^\\"])*$)/g, ""); 

I built this answer from one of my previous answers to a similar but not identical question ; therefore, I will tell you about this for an explanation.

You can test it live on regex101.com .

+2
source

In Javascript, you can use String.replace with a function as a parameter . This way you define match groups, and then you can replace each one individually.

Do you want to combine all spaces

 \s+ 

and you need to combine everything inside the quotes

 (('|")(?:[^\\]\\\2|.)*?\2) 

so you combine it

 var pattern = /\s+|(('|")(?:[^\\]\\\2|.)*?\2)/g 

and you write a replace statement with an anonymous function as a parameter :

 var filteredString = notFilteredString.replace(pattern, function(match, group1) { return group1 || "" }) 

At each match, the function is called to replace the string. A regular expression matches a space or content. The contents of the quote are wrapped as group1 , and the anonymous function returns group1 if group1 matches or nothing "" for spaces or another match.

0
source

Source: https://habr.com/ru/post/1237493/


All Articles