【问题标题】:Regular Expression - replace word except within a URL/URI正则表达式 - 替换除 URL/URI 内的单词
【发布时间】:2011-01-10 21:29:54
【问题描述】:

为 Web 应用程序编写一个全球化模块,我需要一个正则表达式来用另一个词(翻译)替换一个词的所有实例 - 除了 - 在 URL/URI 中找到的词。

编辑:我忘了提到我正在使用 Ruby,所以我不能使用“Lookbehind”

【问题讨论】:

  • 换词做翻译注定要失败。
  • 我试过用这个:'/((?|^)[^
  • Ruby 1.9 支持lookbehind。你用的是 1.8 吗?

标签: ruby regex url replace word


【解决方案1】:
  • 在 URI 正则表达式上拆分;在结果中包含 URI。
  • 对于每件:
    • 如果是 URI,不要管它
    • 否则,请进行单词替换
  • 加入碎片

代码:

# From RFC 3986 Appendix B, with these modifications:
#   o Spaces disallowed
#   o All groups non-matching, except for added outermost group
#   o Not anchored
#   o Scheme required
#   o Authority required
URI_REGEX = %r"((?:(?:[^ :/?#]+):)(?://(?:[^ /?#]*))(?:[^ ?#]*)(?:\?(?:[^ #]*))?(?:#(?:[^ ]*))?)"

def replace_except_uris(text, old, new)
  text.split(URI_REGEX).collect do |s|
    if s =~ URI_REGEX
      s
    else
      s.gsub(old, new)
    end
  end.join
end

text = <<END
stack http://www.stackoverflow.com stack
stack http://www.somewhere.come/stack?stack=stack#stack stack
END

puts replace_except_uris(text, /stack/, 'LINKED-LIST')

# => LINKED-LIST http://www.stackoverflow.com LINKED-LIST
# => LINKED-LIST http://www.somewhere.come/stack?stack=stack#stack LINKED-LIST

【讨论】:

    【解决方案2】:

    您是否尝试过将文本拆分为单词并遍历单词?然后你可以检查每个单词,确定它是否是一个 URI,如果不是,就翻译它。

    【讨论】:

      【解决方案3】:

      你可以使用类似的东西

      (?<!://[^ ]*)\bfoo\b
      

      但这可能并不完美,它只是看起来该词没有出现在单个非空白字符串中,该字符串在该词之前的某处没有://

      PS Home:\> "foo foobar http://foo_bar/baz?gak=foobar baz foo" -replace '(?<!://[^ ]*)\bfoo\b', 'FOO'
      FOO foobar http://foo_bar/baz?gak=foobar baz FOO
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-12-10
        • 1970-01-01
        • 2020-01-06
        • 2015-09-03
        • 2019-07-29
        • 1970-01-01
        相关资源
        最近更新 更多