首页 > 解决方案 > 正则表达式查找不在 URL 路径中的单词实例

问题描述

我想匹配字符串中某个单词的实例,只要该单词不在 URL 中。

一个例子是在下面找到 'hello' 的实例:

hello this is a regex problem http://geocities.com/hello/index.html?hello! Hello how are you!

这个问题最简单的正则表达式是:

/\bhello\b/i

但是,这会返回所有四个“hello”实例,包括 URL 字符串中包含的两个实例。

我已经尝试过对“http”进行负面回顾,但到目前为止没有任何效果。有任何想法吗?

标签: ruby-on-railsregex

解决方案


以下是基于The Best Regex Trick Ever的几种解决方案,用于 1) 计算 URL 之外的匹配项,2) 删除不在 URL 中的匹配项,以及 3) 使用 URL 之外的标记包装匹配项:

s = "hello this is a regex problem http:"+"//geocities.com/hello/index.html?hello! Hello how are you!"
# Counting
p s.scan(/https?:\/\/\S*|(hello)/i).flatten.compact.count
## => 2
# Removing
p s.gsub(/(https?:\/\/\S*)|hello/i, '\1')
## => " this is a regex problem http://geocities.com/hello/index.html?hello!  how are you!"
# Wrapping with a tag
p s.gsub(/(https?:\/\/\S*)|(hello)/i) { $1 || "<span>#{$2}</span>" }
## => "<span>hello</span> this is a regex problem http://geocities.com/hello/index.html?hello! <span>Hello</span> how are you!"

hello如果您需要匹配整个单词,您可以使用单词边界包装模式, \bhello\b.

查看在线 Ruby 演示

笔记

  • .scan(/https?:\/\/\S*|(hello)/i).flatten.compact.counthttp- 匹配以or开头的 URL https,或匹配并捕获helloGroup 1,.scan只返回捕获的子字符串,但nil一旦 URL 匹配,它也会返回,因此.compact需要从ed 数组中删除nil项目并返回数组中的项目数.flatten.count
  • .gsub(/(https?:\/\/\S*)|hello/i, '\1')将 URL 匹配并捕获到 Group 1 中,并且hello只匹配 URL 之外的所有hellos,并且匹配替换为\1,对 Group 1 的反向引用,当找到时它是一个空字符串hello
  • s.gsub(/(https?:\/\/\S*)|(hello)/i) { $1 || "<span>#{$2}</span>" }将 URL 匹配并捕获到组 1 和hellos 到组 2。如果组 1 匹配,则$1将此值放回字符串中,否则,组 2 用标签包装并插入回字符串中。

推荐阅读