i reading regex group matching question , see there 2 ways reference capture groups regex expression, namely,
- match string method e.g.
string.match(/(^.*)(:)(.*)/i).captures - perl-esque capture group variables such $1, $2, etc obtained
if match =~ /(^.*)(:)(.*)/i - update: mentioned 0xcafebabe there third option - last_match method
which better? 1), safety, have use if statement guard against nils why not extract information then? instead of second step calling string captures method. option 2) looks more convenient me.
for simple tasks, directly accessing pseudo variables $1, etc. may short , easier, when things complicated, accessing things via matchdata instances (nearly) way go.
for example, suppose doing nested gsub:
string1.gsub(regex1) |string2| string2.gsub(regex2) ... # impossible/difficult refer match data of outer loop end end within inner loop, suppose wanted refer captured group of outer gsub. calling $1, $2, etc. not give right result because last match data has changed doing inner gsub loop. source of bug.
it necessary refer captured groups via match data:
string1.gsub(regex1) |string2| m1 = $~ string2.gsub(regex2) m2 = $~ ... # match data of outer loop can accessed via `m1`. # match data of inner loop can accessed via `m2`. end end in short, if want short hackish things simple tasks, can use pseudo variables. if want keep code more structured , expandable, should access data through match data.
Comments
Post a Comment