From: Tim Hunter Date: 2004-04-14T08:14:14+09:00 Subject: Re: New Ruby questions... On Tue, 13 Apr 2004 22:10:11 +0000, Jeff Massung wrote: > I've just started Ruby a couple days ago (man this is cool). Coming from > the embedded world of Forth and C, being able to do some string parsing > easily is what I'm looking forward to. So, onto a couple questions that I > can't seem to find the answers to: > > Quickly, the "teach myself" project is a simple ARM assembler. I've done > it numerous times, and it is something I'm familiar and comfortable with > (let alone something I need ATM). > > 1. How can a regexp get the longer of two possibilities that are > ambiguous? For example, I need to be able to strip out register names: > > registers = '(r0|r1|r2|r3...|r10|r11|r12...)' > > In the regular expression, how can I get it to find r10 or r11 instead of > stopping at r1? I get the same problem with opcode mnemonics (like B > instead of BX or BL). > Try this regexp instead: /r\d+/ For example, irb(main):007:0> m = /r\d+/.match('r13') # irb(main):008:0> p m[0] "r13" nil irb(main):009:0> This regular expression matches 'r' followed by one or more digits. Notice that the regexp matched the whole string, not just 'r1'. By default, regexps are "greedy", that is, they want to match as many characters as they can. Of course that's the behavior you're looking for. Your original expression "(r0|r1|r2..." uses the alternation ("|") operator to match one of a set of regular expressions. The regexp "a|b" tries "a" first and if it doesn't match then it tries "b".