使用正则表达式删除开始和结束字符串

时间:2016-06-23 06:44:06

标签: ruby regex string

我需要一个可以消除字符串开头和结尾的正则表达式。例如我:

<br><br><br>hi how are you<br><br><br>hi how are you<br>hi how are you<br>hi how are you<br><br><br><br>

我需要删除开头和结尾,并在字符串的开头加上<br>并结束

<br>hi how are you<br><br><br>hi how are you<br>hi how are you<br>hi how are you<br>

1 个答案:

答案 0 :(得分:2)

str = " <br><br><br>hi how ru<br><br><br>hi how ru<br>hi how ru<br><br><br><br>"

r = /
    \A         # match beginning of string
    (?:<br>)+  # match <br> one or more times
    (?=<br>)   # match <br> in a positive lookahead
    |          # or
    (?<=<br>)  # match <br> in a positive lookbehind
    (?:<br>)+  # match <br> one or more times
    \z         # match end of string
    /x         # free-spacing regex definition mode

str.strip.gsub(r,"")
  #=> "<br>hi how ru<br><br><br>hi how ru<br>hi how ru<br>"

这是另一种不使用正则表达式的方法。

(str.strip).sub(/(?:<br>)+/, "<br>").reverse.sub(/(?:>rb<)+/, ">rb<").reverse
  #=> "<br>hi how ru<br><br><br>hi how ru<br>hi how ru<br>"