为 Web 应用程序编写全球化模块,我需要一个正则表达式来用另一个单词(翻译)替换一个单词的所有实例 - 除了在 URL/URI 中找到的单词。
编辑:我忘了提及我正在使用 Ruby,所以我不能使用“Lookbehind”
- 根据 URI 正则表达式进行拆分;在结果中包含 URI。
- For each piece:
- 连接各个部分
Code:
# 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)