基本上,我試圖使用正則運算式來匹配 Ruby 中包含特殊字符的重復模式。如果我得到模式重復但不是動態的次數,我就能夠做到這一點。我希望匹配的示例字串是:
Draw a square that is {{coords.width}} pixels wide by {{coords.height}} pixels tall.
這可以通過使用輕松完成
arr = value.scan(/\{\{(\w ?\.\w ?)\}\}/).flatten
我運行這個后 arr 看起來像這樣
["coords.width", "coords.height"]
但是我如何撰寫一個可以匹配的正則運算式,以防這種模式任意遵循,例如
Draw a square that is {{shape.rectangle.coords.width}} pixels wide by {{shape.rectangle.coords.height}} pixels tall.
同時在以下情況下也匹配(沒有“。”)
Draw a square that is {{width}} pixels wide by {{height}} pixels tall.
uj5u.com熱心網友回復:
您可以匹配正則運算式
r = /(?<=\{\{)[a-z] (?:\.[a-z] )*(?=\}\})/
regex 101.com 上的Rubular 演示/ PCRE 演示
我已經包含了 PCRE 演示,因為 regex101.com 提供了正則運算式的每個元素的詳細解釋(懸停游標)。
例如,
str = "Draw a square {{coords.width}} wide by {{coords.height}} "
"tall by {{coords deep}} deep"
str.scan(r)
#=> ["coords.width", "coords.height"]
請注意,"coords deep"它不匹配,因為它沒有(我假設的是)有效形式。另請注意,scan由于正則運算式沒有捕獲組,因此我不必展平回傳值。
我們可以以自由間距模式撰寫正則運算式以使其自檔案化。
/
(?<= # begin a positive lookbehind
\{\{ # match 1 or more lower case letters
) # end the positive lookbehind
[a-z] # match 1 or more lower case letters
(?: # begin a non-capture group
\. # match a period
[a-z] # match 1 or more lower case letters
) # end the non-capture group
* # execute the non-capture group zero or more times
(?= # begin a positive lookahead
\}\} # match '}}'
) # end positive lookahead
/x # free-spacing regex definition mode
uj5u.com熱心網友回復:
(/\{\{(.*?)\}\}/)
這成功了。它匹配 {{}} 內的任何內容,但我始終可以在提取出現次數/模式時驗證結構
uj5u.com熱心網友回復:
(\{ \S )
上面的模式將實作您的目標。它匹配外殼內的所有非空格字符。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/326782.html
下一篇:無法按字母順序比較字串
