Matt
Matt

Reputation: 426

Regular expression for float/double numbers

I've been trying to retrieve a string and 2 decimal numbers from a sentence, but the decimal part hasn't been working well.

The sentence I have is on this format: AMBIENT_CAVE 0.5 1 So it would be word (sometimes containing _) then 2 numbers that could be either integer (1 or 0) or a decimal between 0 and 1.

My current regular expression is: (\w+) ([+-]?([0-9]*[.])?[0-9]+) ([+-]?([0-9]*[.])?[0-9]+) Which kinda works, but using the sentence example from above group 3 would be 0..

Results:

enter image description here

I only want AMBIENT_CAVE, 0.5 and 1.
Anyone know how to do it?

Upvotes: 1

Views: 148

Answers (2)

Andy Turner
Andy Turner

Reputation: 140329

Add a ?: to any group you don't want to capture:

(\w+) ([+-]?(?:[0-9]*[.])?[0-9]+) ([+-]?(?:[0-9]*[.])?[0-9]+)
             ^                           ^

Upvotes: 3

nesteant
nesteant

Reputation: 1068

You can try this one. Please provide more examples of available strings in order to optimize an expression

  (\w+)\s([\d\.]+)\s([\d\.]+)

Upvotes: 1

Related Questions