我有一些具有相同模式的字串:
"abc 1x de" "abc 2x rf" "abc 3x gh"
我需要選擇“x”和“x”之前的數字。我怎樣才能做到這一點?謝謝。
uj5u.com熱心網友回復:
["abc 1x de","abc 2x rf","abc 3x gh","4x ABC" "ABC 5x"].map { |s| s[/(?>\dx)/] }
=> ["1x", "2x", "3x", "4x"]
uj5u.com熱心網友回復:
只需\b使用String#scan檢查單詞邊界即可。使用 Ruby 3.0.2:
["abc 1x de", "abc 2x rf", "abc 3x gh", "4x ABC", "ABC 5x"].
flat_map { _1.scan /\b(?:\d x)\b/ }
#=> ["1x", "2x", "3x", "4x", "5x"]
只要x沒有出現在您的其他字串中,無論您有多少位數字,或者子字串在您的字串中出現的位置,這都將起作用。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/321203.html
標籤:红宝石
