Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 什么';这样做的方法是什么?_Ruby_Regex - Fatal编程技术网

Ruby 什么';这样做的方法是什么?

Ruby 什么';这样做的方法是什么?,ruby,regex,Ruby,Regex,我刚才写了一些类似的东西,我知道一定有一种更漂亮的方式来做这件事 if REGEX.match(foostring) match = REGEX.match(foostring) #do things with match data end 有人知道吗?你可以 /<reg_exp>/.match('foostring') do |match| #do things with match data end /.match('foostring')不匹配| #使用

我刚才写了一些类似的东西,我知道一定有一种更漂亮的方式来做这件事

if REGEX.match(foostring) 
   match = REGEX.match(foostring)
   #do things with match data
end
有人知道吗?

你可以

/<reg_exp>/.match('foostring') do |match|
   #do things with match data
end
/.match('foostring')不匹配|
#使用匹配数据进行操作
结束

返回描述匹配的
MatchData
对象,如果不存在匹配,则返回
nil
。如果给定一个块,如果匹配成功,则使用MatchData调用该块

你能行

/<reg_exp>/.match('foostring') do |match|
   #do things with match data
end
/.match('foostring')不匹配|
#使用匹配数据进行操作
结束

返回描述匹配的
MatchData
对象,如果不存在匹配,则返回
nil
。如果给定一个块,如果匹配成功,则使用MatchData调用该块


更好的解决方案是使用regex匹配块

string.match(/regex/) do |match|
  ...
end
这就是红宝石的风格


请注意,当运行
string.match(/regex/)
时,您也可以通过全局变量
$1
访问匹配。更好的解决方案是将regex匹配与块一起使用

string.match(/regex/) do |match|
  ...
end
这就是红宝石的风格


请注意,当您运行
string.match(/regex/)

时,您也可以通过全局变量
$1
访问匹配。我尝试了“if match=/regex/.match(string)”,但它对我产生了影响。我尝试了“if match=/regex/.match(string)”但它对我产生了影响。噢。我想我一定是把正则表达式搞砸了,在尝试时出错了。谢谢哦我想我一定是把正则表达式搞砸了,在尝试时出错了。谢谢我想知道ruby是否有$cap符号,这太棒了。如果你使用命名捕获组,你可以编写更好的代码“hello little world”。match(/hello(?.*)/)do | match | puts match[:foo]endI想知道ruby是否有$cap符号,这太棒了。如果你使用命名捕获组,你可以编写更好的代码“hello little world”.match(/hello(?.*)/)do | match | put match[:foo]结束