Reputation: 37
Is it possible to replace a character sequence with a newline (\s~\s in this example) and also remove spaces in the beginning and at the end with one regular expression? The number of lines must be flexible.
Input:
foo = 1 ~ bar = 2 ~ baz = 3 ~ ... <- also spaces at the end
Desired output:
foo = 1
bar = 2
baz = 3
... <- no spaces here
I got it working so far, the problem is that my result still has the spaces at the end of the last line:
My current regex search and replace (https://regexr.com/444au):
# search
/(\s*)([^~\s]{1}.*?)(\s~\s)(?=.*)(\s*)/g
# replace
$2\n
Upvotes: 0
Views: 160
Reputation: 371019
One option is to alternate between the \s~\s
and \s+$
, thereby matching the trailing spaces at the very end:
\s*([^~\s].*?)(?:\s~\s+|\s+$)
replace with
$1\n
Note that since the only group you actually care about is the one with [^~\s]{1}.*?
, you can remove all other capturing groups. {1}
is a meaningless quantifier, so you can remove that as well, and (?=.*)
won't do anything - any position in the string will be followed by zero or more characters regardless, so feel free to remove that lookahead.
Upvotes: 1