ruby-on-rails - 正则表达式查找不在 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”进行负面回顾,但到目前为止没有任何效果。有任何想法吗?
解决方案
以下是基于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
.
笔记
.scan(/https?:\/\/\S*|(hello)/i).flatten.compact.count
http
- 匹配以or开头的 URLhttps
,或匹配并捕获hello
Group 1,.scan
只返回捕获的子字符串,但nil
一旦 URL 匹配,它也会返回,因此.compact
需要从ed 数组中删除nil
项目并返回数组中的项目数.flatten
.count
.gsub(/(https?:\/\/\S*)|hello/i, '\1')
将 URL 匹配并捕获到 Group 1 中,并且hello
只匹配 URL 之外的所有hello
s,并且匹配替换为\1
,对 Group 1 的反向引用,当找到时它是一个空字符串hello
。s.gsub(/(https?:\/\/\S*)|(hello)/i) { $1 || "<span>#{$2}</span>" }
将 URL 匹配并捕获到组 1 和hello
s 到组 2。如果组 1 匹配,则$1
将此值放回字符串中,否则,组 2 用标签包装并插入回字符串中。
推荐阅读
- bash - 检索jenkins env变量的shell错误替换错误
- java - 如何连接两个字符串并省略可能的重复单词?
- python - 在 Anaconda 中导入漂亮表的问题
- amazon-web-services - SVL_MV_REFRESH_STATUS 未填充其所有字段
- javascript - AFRAME 三.js 性能提升
- javascript - AlpineJS 多级滑动移动菜单
- json - 使用从 JSON 配置文件中读取的值进行参数喷溅
- node.js - 告诉用户您在地图回调中传递了一个值
- c# - 如何通过代理连接到 Azure 服务总线主题 - C#?
- html - 部署受阻