Sorry this is such an absurdly simple question, but I can’t find the
answer
after some googling, probably just me not knowing how to look.
Anyway, I have a simple string in the format 1a2+3 and want to basically
take out the non-number bits and put the numbers into an array.
It also has to match more than single-digit numbers. The rest is simple
enough, but I’m just really new to regex and can’t make it work.
Anyone feel like helping me out a little, or at least pointing me in the
right direction? Thanks.
On 8/4/06, RJ Melton [email protected] wrote:
Anyway, I have a simple string in the format 1a2+3 and want to basically
take out the non-number bits and put the numbers into an array.
It also has to match more than single-digit numbers.
I’m pretty sure this is non-optimal, but you could use String.split:
“1a23+4-123”.split(/[^\d]/)
the argument to split is a regex that matches anything that’s not a
digit ( \d is a digit; [^\d] is anything but that). split uses that
argument to decide where to split the string up.
;D
I tried that and it works fine, optimal or not. Thanks. 
What about “1a2+b”.scan(/\d+) ?
It returns the numbers as array.
RJ Melton schrieb:
On 8/4/06, Robert R. [email protected] wrote:
What about “1a2+b”.scan(/\d+) ?
It returns the numbers as array.
Muuuuch better!
On 8/4/06, Daniel B. [email protected] wrote:
http://danielbaird.com (TiddlyW;nks! :: Whiteboard Koala :: Blog ::
Things That Suck)
Will this pick up negative numbers or floats?
On 8/4/06, Robert R. [email protected] wrote:
What about “1a2+b”.scan(/\d+) ?
It returns the numbers as array.
Will this pick up negative numbers or floats?
Nope, only plain digits. if you want other stuff, you need to add it
to the regex.
/\d+/ …is just digits
/[±]?\d+/ …optional + or -
/[±]?\d+.?\d*/ …optional + or -, and optional .
untested… (sorry, too lazy to test 
p “-1.2 56 0.443 4.22E-12 000555”.scan(
/(?:[±])?[0-9]+(?:[,.][0-9]+)?(?:E[±][1-9][0-9]*)?/ )
#=> ["-1.2", “56”, “0.443”, “4.22E-12”, “000555”]
This looks okay for most purposes, in my opinion. 
You can google for “real number regex” et cetera…
Daniel B. schrieb: