我有一個字串,想從中洗掉所有具有以下屬性的子字串:
1. They start with an arbitrary (non-zero) number of open parenthesis
2. Then follows an arbitrary set of word characters (`\w`)
3. Then follows the same number of closing parenthesis as there have been open parenthesis.
純正則運算式不能匹配左括號和右括號。我第一次嘗試尋找一種動態使用反向參考的方法。我知道這不是有效的 Ruby,但給你一個想法:
sttrep = str.gsub(/([(] ) \w [)]#{\1.size}/x, '')
當然 \1.size 是無效的;但是有沒有一種使用插值的方法,我可以根據反向參考來評估一些東西?
另一種可能是gsub在回圈中重復使用并一次洗掉一層括號:
tmpstr = str
loop do
strrep = tmpstr.gsub(/[(] ([(]\w [)]) [)]/x, "(\\1)")
if tmpstr == strrep
# We only have one level of parenthesis to consider
sttrep = str.gsub(/[(]\w [)]/x, '')
break
else
tmpstr = strrep
end
end
# strrep is now the resulting string
然而,這似乎是一個過于復雜的解決方案。有什么想法(當然除了撰寫我的歐文字串決議器,它遍歷每個字符并計算括號)?
更新:
示例 1:
str = "ab((((cd))))ef((gh))ij(kl)mn"
strrep應該包含abefijmn。
示例 2:
str = "((((abc));def;((ghi)))"
strrep應該包含(;def;)。
uj5u.com熱心網友回復:
通常,要匹配您描述的字串,您需要使用正則運算式子例程:
(\((?:\w |\g<1>)?\))
請參閱正則運算式演示。
詳情:
(\((?:\w |\g<1>)?\))- 第 1 組(出于遞回目的需要捕獲):\(- 一個(字符(?:\w |\g<1>)?- 一個或多個單詞字符或第 1 組模式的可選出現遞回\)- 一個)字符。
為了使其更高效,請考慮使用原子組而不是非捕獲組:
(\((?>\w |\g<1>)?\))
^^
請參閱Ruby 演示:
puts [
'ab((((cd))))ef((gh))ij(kl)mn',
'((((abc));def;((ghi)))',
'(((foo)) , bar)'
].map {|x| x.gsub(/(\((?:\w |\g<1>)?\))/, '')}
輸出:
abefijmn
((;def;)
( , bar)
uj5u.com熱心網友回復:
據我了解,您不需要決議任何“復雜”的東西,例如任意 S 運算式等-您感興趣的只是消除諸如(((foo)))和之類的東西((bar))(它們具有相同數量的打開/關閉括號)但是保持(((foo)) bar)原樣。
如果這個假設是正確的,那么很簡單gsub就可以完成這項作業:
def delete_parentheses(str)
str.gsub(/(\( )\w (\) )/) do |match|
$1.size == $2.size ? "" : match
end
end
delete_parentheses("Here ((be)) dragons") # => Here dragons
delete_parentheses("Here ((be) dragons") # Here ((be) dragons
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/495307.html
上一篇:如何用隨機元素填充二維陣列?
