从Rails中的字符串中删除特定的正则表达式
问题描述:
我在构建一个类似tweet的系统,其中包含@mentions和#hashtags。现在,我需要一个鸣叫会来这样的服务器:从Rails中的字符串中删除特定的正则表达式
hi [@Bob D](member:Bob D) whats the deal with [#red](tag:red)
,并在数据库中保存为:
hi @Bob P whats the deal with #red
我的代码是什么样的流程在我的脑海中,但无法实现它的工作。基本上,我需要执行以下操作:
- 扫描字符串任何
[@...]
(一个样结构阵列,其具有@
开始) - 状结构的阵列后删除paranthesis(因此对于
[@Bob D](member:Bob D)
,除去一切在paranthesis) - 删除周围与
@
(意思是开头的子串的括号中,删除从[]
[@...]
)
我也将需要为#
做同样的事情。我几乎可以肯定,这可以通过使用正则表达式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
与上面的代码的问题是,我想不通的正则表达式,并没有摆脱括号。
答
此正则表达式应该为此 /(\[(@.*?)\]\((.*?)\))/
工作,你可以使用这个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
+0
作为摆脱括号,.gsub!(“[”,“”).gsub!(“]”,“”)将工作,但它会删除所有括号 –
答
考虑一下:
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"
的时间越长,或更复杂的模式,维护或更新就越困难,所以尽量保持它们的小。从简单的模式构建复杂的模式,因此更容易调试和扩展。
请阅读“[mcve]”。你无法弄清楚正则表达式?那么,向我们展示你的尝试,以便我们能够纠正它,而不是抛出代码。 SO在这里是为了帮助你,但更多的是在未来帮助其他人类似的问题,但除非你展示你的尝试,否则我们不能这样做。没有你的企图的证据,看起来你没有试图让我们为你写。 –
你为什么要把''Bob D''改成''“Bob P”'? –