Reputation: 2592
I want to replace a string, but preserve the outer white space, if that makes sense.
Ex:
" Hello world "
To:
" Whatever I want "
I figured there was a quick way to do this via regular expressions, but I can't figure it out. Any help would be appreciated. Thanks!
Upvotes: 0
Views: 1011
Reputation: 31468
In Ruby this works
" this is a message ".gsub /^(\s*)(.*?)(\s*$)/, '\1and this is another\3'
=> " and this is another "
Upvotes: 2
Reputation: 10580
To replace " Hello world "
to " Whatever you Want "
, you can do something like:
"^\s*(.*?)\s*$"
Upvotes: 0
Reputation: 437914
Generally speaking, a regex that greedily matches ^\s*(.*)\s*$
and replaces the first capture group (inside the parens) should do it. But the particulars depend on the flavor of regex you are using.
Upvotes: 0