Replace string but preserve whitespace
I want to replace a string, but preserve the outer 开发者_JAVA技巧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!
In Ruby this works
" this is a message ".gsub /^(\s*)(.*?)(\s*$)/, '\1and this is another\3'
=> " and this is another "
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.
To replace " Hello world " to " Whatever you Want ", you can do something like:
"^\s*(.*?)\s*$"
加载中,请稍侯......
精彩评论