开发者

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*$"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜