如何使用正则表达式在字符串中查找特定匹配项
How to find specific matches in a string using regex
我有这样的字符串
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"]]
您可以使用
\AView_Export_(US_(?:GoM|Horizontals|Onshore))(?:_(Ultimate))?_(\w+)
见regex demo。 详情:
\A
- 字符串的开头(Ruby 正则表达式中的 ^
表示任何行的开头)
View_Export_
- 固定字符串
(US_(?:GoM|Horizontals|Onshore))
- 第 1 组:US_
字符串,然后是 GoM
、Horizontals
或 Onshore
字
(?:_(Ultimate))?
- 下划线和 Ultimate
单词的可选序列
_
- 下划线
(\w+)
- 第 3 组:任何一个或多个单词字符。
参见 Ruby demo:
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
我有这样的字符串
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"]]
您可以使用
\AView_Export_(US_(?:GoM|Horizontals|Onshore))(?:_(Ultimate))?_(\w+)
见regex demo。 详情:
\A
- 字符串的开头(Ruby 正则表达式中的^
表示任何行的开头)View_Export_
- 固定字符串(US_(?:GoM|Horizontals|Onshore))
- 第 1 组:US_
字符串,然后是GoM
、Horizontals
或Onshore
字(?:_(Ultimate))?
- 下划线和Ultimate
单词的可选序列_
- 下划线(\w+)
- 第 3 组:任何一个或多个单词字符。
参见 Ruby demo:
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