为什么这不起作用?它虽然在Rubular中有效

时间:2014-05-06 01:13:52

标签: regex

text.gsub!(/(?<!http:\/\/)www\.(?=\w)/,'http://www.')

是我所拥有的......它表示未定义(?...)序列。当我在rubular中使用(?<!http:\/\/)www\.(?=\w)时,它就能满足我的需求,但是这对我不起作用,所以我需要一些帮助。

这应该替换www. to http://www.这是一个类的功课,所以它必须做到这一点。

非常感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

试试这个:

text.gsub(/^(?!http:\/\/)www(.*?)$/, 'http://www\1')

Regex demo

它替换了www的所有实例,而不是http://之前的http://www.something.com

正则表达式解释

Assert position at the beginning of a line (at beginning of the string or after a line break character) «^»
Assert that it is impossible to match the regex below starting at this position (negative lookahead) «(?!http://)»
   Match the characters “http://” literally «http://»
Match the characters “www” literally «www»
Match the regular expression below and capture its match into backreference number 1 «(.*?)»
   Match any single character that is not a line break character «.*?»
      Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Assert position at the end of a line (at the end of the string or before a line break character) «$»