Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex to remove new line and spaces

I created a regex to get rid of spaces, tabs, new lines, etc.

(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+

My issue is that it matches some spaces and some new lines, not all of them. Why is that?

I have tried:

(^[\r\n]*|[\r\n]+)[\s\t+]*[\r\n]+

but still doesn't seem to match multiple spaces

Regex tester demo

like image 619
user4756836 Avatar asked Nov 20 '22 12:11

user4756836


1 Answers

I'm not quite sure what you want to achieve here. But if you, as you state in the question, just ** all you have to do is replace \s with nothing. See regex101. (replacing with * for clarity)

The problem with your regex is (besides from it being overly complex ;) that the ending [\r\n]+ requires a CR/LF and, if the line isn't preceded by an empty line (^[\r\n] matches a line beginning with a linefeed - i.e. an empty line), the [\r\n]+ in the first also requires a CR/LF.

In short - it will never match two consecutive non empty lines.

Regards.

like image 117
SamWhan Avatar answered Nov 23 '22 02:11

SamWhan