简体   繁体   中英

regex ruby gsub: inserting space between characters in capture group

I am trying to to convert strings like:

"foo(bar baz)bom" => "foo (bar baz) bom"

I have this so far:

"foo(bar baz)bom".gsub(/((\S\()|(\)\S))/,'\1')

But I am not sure what to do with the '\\1' to insert a space between the parens and the character.

Thanks!

Do as below

>> "foo(bar baz)bom".gsub(/[)(]/,"(" =>" (",")" =>") ")
=> "foo (bar baz) bom"
>> 

update

>> "foo (bar baz)bom".gsub(/(?<=\S)\(|\)(?=\S)/,"(" =>" (",")" =>") ")
=> "foo (bar baz) bom"
>> "foo(bar baz)bom".gsub(/(?<=\S)\(|\)(?=\S)/,"(" =>" (",")" =>") ")
=> "foo (bar baz) bom"
>> "foo(bar baz) bom".gsub(/(?<=\S)\(|\)(?=\S)/,"(" =>" (",")" =>") ")
=> "foo (bar baz) bom"
>> 

"foo(bar baz)bom".gsub(/((?<! )\\(|\\)(?! ))/,"(" =>" (",")" =>") ")

会成功的

This is easier:

"foo(bar baz)bom".gsub(/(?<!\s)(?=\()|(?<=\))(?!\s)/, " ")
# => "foo (bar baz) bom"

You were on the right track with \\S\\)|\\)\\S :

"foo(bar baz)bom".gsub /(?=\S\(|\)\S)(.)(.)/, '\1 \2'
#=> "foo (bar baz) bom"

If you don't absolutely have to use gsub, you can do it this way. It's more verbose, but to me it's easier to read than long complex regular expressions:

s = "foo(bar baz)bom"
while s =~ /\w\(/
  s = $` + $&[0] + ' (' + $'
end
while s =~ /\)\w/
  s = $` + ') ' + $&[1] + $'
end

Like I say, it's verbose. But it's straightforward and there's no guesswork.

Of course you can replace

$` + $&[0] + ' (' + $'

with

"#{$`}#{$&[0]} (#{$'}"

if you prefer to use string interpolation rather than + or <<. But I think the first form is easier to read.

If you aren't familiar with this notation, $` is the part of the string before the match, $& is the matched string, and $' is the part after the match. It's easy to remember which is which because it's left to right on your keyboard.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM