【发布时间】: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
我脑子里有代码的样子,但无法让它工作。基本上,我需要做到以下几点:
- 扫描字符串以查找任何
[@...](以@开头的类似数组的结构) - 删除类数组结构后的括号(所以对于
[@Bob D](member:Bob D),删除括号中的所有内容) - 删除以
@开头的子字符串周围的括号(意思是从[@...]中删除[])
我也需要为# 做同样的事情。我几乎可以肯定这可以通过使用正则表达式 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