Dan*_*ley 95 ruby regex string
我正在寻找一种在Ruby中对字符串执行正则表达式匹配的方法,并在第一次匹配时使其短路.
我正在处理的字符串很长,看起来标准方式(match方法)会处理整个事物,收集每个匹配,并返回包含所有匹配项的MatchData对象.
match = string.match(/regex/)[0].to_s
Run Code Online (Sandbox Code Playgroud)
Pre*_*ten 131
你可以试试variableName[/regular expression/].这是irb的示例输出:
irb(main):003:0> names = "erik kalle johan anders erik kalle johan anders"
=> "erik kalle johan anders erik kalle johan anders"
irb(main):004:0> names[/kalle/]
=> "kalle"
Run Code Online (Sandbox Code Playgroud)
Ben*_*ier 58
你可以使用[]:(就像match)
"foo+account2@gmail.com"[/\+([^@]+)/, 1] # matches what is inside ()
# => "account2"
"foo+account2@gmail.com"[/\+([^@]+)/, 0] # matches whole regexp
# => "+account2"
Run Code Online (Sandbox Code Playgroud)
Sla*_*ast 22
如果只有匹配的存在是重要的,你可以去
/regexp/ =~ "string"
Run Code Online (Sandbox Code Playgroud)
无论哪种方式,match只应返回第一个scan匹配,同时搜索整个字符串.因此如果
matchData = "string string".match(/string/)
matchData[0] # => "string"
matchData[1] # => nil - it's the first capture group not a second match
Run Code Online (Sandbox Code Playgroud)
我尚不确定此功能是很棒还是完全疯狂,但是您的正则表达式可以定义局部变量。
/\$(?<dollars>\d+)\.(?<cents>\d+)/ =~ "$3.67" #=> 0
dollars #=> "3"
Run Code Online (Sandbox Code Playgroud)
(摘自http://ruby-doc.org/core-2.1.1/Regexp.html)。