簡體   English   中英

Ruby正則表達式替換某些序列

[英]Ruby regexp for replace some sequence

我如何轉換字符串-

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

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

我嘗試使用next- text.gsub(/\\s\\n/, '\\n') ,但是它添加了其他斜杠-

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

使用雙引號,而不是單引號:

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

\\n用單引號一個接一個地表示\\n的含義。 如果為double,則將其解釋為換行符。

我希望"test1"之后的空格也要刪除,或者"test2"之后的空格也不要刪除。 @ndn假定前者是故意的。 如果適用第二種解釋,則可以執行以下操作:

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"

要么:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM