【问题标题】:Remove certain regex from a string in Rails从 Rails 中的字符串中删除某些正则表达式
【发布时间】:2017-06-01 16:31:56
【问题描述】:

我正在构建一个类似推文的系统,其中包括@mentions 和#hashtags。现在,我需要将一条推文发送到服务器,如下所示:

hi [@Bob D](member:Bob D) whats the deal with [#red](tag:red)

并将其保存在数据库中:

hi @Bob P whats the deal with #red

我脑子里有代码的样子,但无法让它工作。基本上,我需要做到以下几点:

  1. 扫描字符串以查找任何[@...](以@ 开头的类似数组的结构)
  2. 删除类数组结构后的括号(所以对于[@Bob D](member:Bob D),删除括号中的所有内容)
  3. 删除以@开头的子字符串周围的括号(意思是从[@...]中删除[]

我也需要为# 做同样的事情。我几乎可以肯定这可以通过使用正则表达式 slice! 方法来完成,但我真的很难想出所需的正则表达式和控制流。 我想应该是这样的:

a = "hi [@Bob D](member:Bob D) whats the deal with [#red](tag:red)"
substring = a.scan <regular expression here>
substring.each do |matching_substring|  #the loop should get rid of the paranthesis but not the brackets
    a.slice! matching_substring
end
#Something here should get rid of brackets

上面代码的问题是我无法弄清楚正则表达式并且它没有去掉括号。

【问题讨论】:

  • 请阅读“minimal reproducible example”。你无法弄清楚正则表达式?好吧,告诉我们你尝试了什么,这样我们就可以更正它,而不是仅仅扔掉代码。 SO 在这里帮助您,但更多的是帮助将来遇到类似问题的其他人,但除非您展示您的尝试,否则我们不能这样做。如果没有您尝试的证据,您似乎并没有尝试并希望我们为您编写它。
  • 你为什么要把"Bob D"改成"Bob P"

标签: ruby-on-rails ruby regex ruby-on-rails-5 slice


【解决方案1】:

这个正则表达式应该适用于此 /(\[(@.*?)\]\((.*?)\))/

你可以用这个rubular来测试它

那个?在 * 之后使其不贪婪,因此它应该捕获每个匹配项

代码看起来像

a = "hi [@Bob D](member:Bob D) whats the deal with [#red](tag:red)"
substring = a.scan (\[(@.*?)\]\((.*?)\))
substring.each do |matching_substring|
  a.gsub(matching_substring[0], matching_substring[1]) # replaces [@Bob D](member:Bob D) with @Bob D
  matching_substring[1] #the part in the brackets sans brackets
  matching_substring[2] #the part in the parentheses sans parentheses
end

【讨论】:

  • 至于去掉括号, .gsub!("[", "").gsub!("]","") 会起作用,但它会删除所有括号
【解决方案2】:

考虑一下:

str = "hi [@Bob D](member:Bob D) whats the deal with [#red](tag:red)"

BRACKET_RE_STR = '\[
              (
                [@#]
                [^\]]+
              )
              \]'
PARAGRAPH_RE_STR = '\(
              [^)]+
              \)'


BRACKET_RE = /#{BRACKET_RE_STR}/x
PARAGRAPH_RE = /#{PARAGRAPH_RE_STR}/x
BRACKET_AND_PARAGRAPH_RE = /#{BRACKET_RE_STR}#{PARAGRAPH_RE_STR}/x

str.gsub(BRACKET_AND_PARAGRAPH_RE) { |s| s.sub(PARAGRAPH_RE, '').sub(BRACKET_RE, '\1') }
# => "hi @Bob D whats the deal with #red"

模式越长或越复杂,维护或更新就越困难,因此请尽可能减小它们。从简单的模式构建复杂的模式,以便更容易调试和扩展。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-28
    • 1970-01-01
    • 1970-01-01
    • 2021-01-17
    • 2014-06-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多