简体   繁体   中英

Ruby regexp for replace some sequence

How I can convert string -

text = "test test1 \n \n \n \n \n \n \n \n \n \n \n \n \n \n test2 \n"

to

test test1 \n\n\n\n\n\n\n\n\n\n\n\n\n\n test2\n

I tried use next - text.gsub(/\\s\\n/, '\\n') , but it added additional slash -

test test1\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n test2\\n

Use double quotes, instead of single:

text.gsub(/\s\n/, "\n")

With single quotes, \\n has the meaning of \\ and n , one after another. With double, it is interpreted as new line.

I expect that either the space after "test1" is to be removed as well or the space after "test2" is not to be removed. @ndn assumed the former was intended. If the second interpretation applies, you could do the following:

r = /
    (?<=\n) # match \n in a positive lookbehind
    \s      # match a whitespace character
    (?=\n)  # match \n in a positive lookahead
    /x      # extended/free-spacing regex definition mode

text.gsub(r,"")
    #=> "test test1 \n\n\n\n\n\n\n\n\n\n\n\n\n\n test2 \n"

or:

text.gsub(/\n\s(?=\n)/, "\n")

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