正则表达式 - 替换 URL/URI 之外的单词 [英] Regular Expression - replace word except within a URL/URI

查看:45
本文介绍了正则表达式 - 替换 URL/URI 之外的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Writing a globalization module for a web application and I need a regexp to replace all instances of a word with another word (the translation) - except - words found within a URL/URI.

我忘了提到我使用的是 Ruby,所以我不能使用Lookbehind"

I forgot to mention that I'm using Ruby, so I can't use 'Lookbehind'

推荐答案

  • 在 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
      

      这篇关于正则表达式 - 替换 URL/URI 之外的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆