簡體   English   中英

從Rails的字符串中刪除某些正則表達式

[英]Remove certain regex from a string in Rails

我正在構建一個類似於@tweet的系統,其中包括@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!來完成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

上面的代碼的問題是我無法弄清楚正則表達式,並且它也沒有擺脫括號。

此正則表達式適用於/(\\[(@.*?)\\]\\((.*?)\\))/

你可以用這個石頭來測試

*表示非貪婪之后,因此應該捕獲每個匹配項

代碼看起來像

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

考慮一下:

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"

模式越長或越復雜,維護或更新就越困難,因此請使其盡可能小。 從簡單的模式構建復雜的模式,以便於調試和擴展。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM