我有像這樣的字串
View_Export_US_Horizontals_Ultimate_DirectionalSurveys
我想提取匹配項
[["US_Horizontals", "Ultimate", "DirectionalSurveys"]] //String Ultimate may or may not be present
我有以下正則運算式,/^View_Export_(US\_(GoM|Horizontals|Onshore))((_Ultimate)?)_(\w )/
但我得到以下匹配陣列
[["US_Horizontals", "Horizontals", "_Ultimate", "_Ultimate", "DirectionalSurveys"]]
我如何跳過像Horizontals&這樣的字串,_Ultimate然后得到一個像這樣的陣列
[["US_Horizontals", "Ultimate", "DirectionalSurveys"]]
要么
[["US_Horizontals", "DirectionalSurveys"]]
uj5u.com熱心網友回復:
您可以使用
\AView_Export_(US_(?:GoM|Horizontals|Onshore))(?:_(Ultimate))?_(\w )
請參閱正則運算式演示。詳情:
\A- 字串的開頭(^在 Ruby 正則運算式中表示任何行的開頭)View_Export_- 固定字串(US_(?:GoM|Horizontals|Onshore))- 第 1 組:US_字串,然后是GoM,Horizontals或Onshore單詞(?:_(Ultimate))?- 下劃線和Ultimate單詞的可選序列_- 一個下劃線(\w )- 第 3 組:任何一個或多個單詞字符。
請參閱Ruby 演示:
string = "View_Export_US_Horizontals_Ultimate_DirectionalSurveys"
rx = /\AView_Export_(US_(?:GoM|Horizontals|Onshore))(?:_(Ultimate))?_(\w )/
one, two, three = string.match(rx).captures
puts one #=> US_Horizontals
puts two #=> Ultimate
puts three #=> DirectionalSurveys
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/445706.html
上一篇:來自S3檔案的Zip檔案
