草庐IT

MatchData

全部标签

ruby - 如何用 MatchData 对象替换 Perl 风格的正则表达式

我正在使用带有正则表达式的gsub方法:@text.gsub(/(-\n)(\S+)\s/){"#{$2}\n"}输入数据示例:"Thewolverineisnowes-sentiallyabsentfromthesouthernendofitsEuropeanrange."应该返回:"ThewolverineisnowessentiallyabsentfromthesouthernendofitsEuropeanrange."该方法工作正常,但rubocop报告和冒犯:AvoidtheuseofPerl-stylebackrefs.关于如何使用MatchData对象而不是$2重写它有

ruby - 正则表达式 : how to get every group of MatchData?

我有以下正则表达式:regexp=/(\w+)\s*:\s*(\w+)\s+(.*)\s*;?/ix我正在尝试获取捕获:names,direction,type=iotext.match(regexp).captures这适用于单个“x:整数;”,但是我怎样才能在我的文件中获取所有其他匹配数据组:"x:ininteger;y:inlogic;z:infloat;" 最佳答案 您的正则表达式regexp没问题,它只匹配一次。如果你想匹配每一次出现尝试"x:ininteger;y:inlogic;z:infloat;".scan(reg

ruby - 如何检查命名组是否存在于 MatchData 对象中?

ruby-1.9.2-p180:003>result="teststring".match(/(?test)/)=>#ruby-1.9.2-p180:011>result["mtch"]=>"test"ruby-1.9.2-p180:012>result["fail"]IndexError:undefinedgroupnamereference:failfrom(irb):12:in`[]'from(irb):12from/Users/jeremysmith/.rvm/rubies/ruby-1.9.2-p180/bin/irb:16:in`'没有用于检查命名组是否存在的MatchDa
12