我正在寻找一种方法,在Ruby中对字符串执行正则表达式匹配,并在第一次匹配时使其短路。
我正在处理的字符串很长,从外观上看,标准方法(match
方法)将处理整个字符串,收集每个匹配项,并返回一个包含所有匹配项的MatchData对象。
match = string.match(/regex/)[0].to_s
发布于 2009-02-06 08:53:30
您可以尝试String#[]
(就像在variableName[/regular expression/]
中一样)。
以下是IRB的输出示例:
names = "erik kalle johan anders erik kalle johan anders"
# => "erik kalle johan anders erik kalle johan anders"
names[/kalle/]
# => "kalle"
发布于 2014-04-22 23:19:21
您可以使用[]
:(类似于match
)
"foo+account2@gmail.com"[/\+([^@]+)/, 1] # matches capture group 1, i.e. what is inside ()
# => "account2"
"foo+account2@gmail.com"[/\+([^@]+)/] # matches capture group 0, i.e. the whole match
# => "+account2"
发布于 2009-02-06 08:59:32
如果只有一个匹配项的存在是重要的,你可以使用
/regexp/ =~ "string"
无论哪种方式,match
应该只返回第一个匹配项,而scan
会搜索整个字符串。因此,如果
matchData = "string string".match(/string/)
matchData[0] # => "string"
matchData[1] # => nil - it's the first capture group not a second match
https://stackoverflow.com/questions/519572
复制相似问题