Homar
Homar

Reputation: 1519

Regular Expression matching floating point numbers not ending with

I'm trying to extract CSS positions from a string - example:

"top left bottom right center 0 0% 50% 100% 360deg 15.5% -16.3%"

The problem is that the string also contains an angle "360deg". I don't want any numbers followed by "deg" to be matched by the regular expression. Currently, I have:

(-?([0-9]*\.[0-9]+|[0-9]+))|(center)|(top)|(left)|(bottom)|(right)

This matches all the numbers (inc. the angle - which I don't want). I have tried using a negative lookahead:

(-?([0-9]*\.[0-9]+|[0-9]+))(?!deg)|(center)|(top)|(left)|(bottom)|(right)

But this only appears to remove the ending zero from 360deg - i.e. 360deg => 36

Does anyone know why the negative lookahead is not successful in removing the angle?

Upvotes: 2

Views: 574

Answers (2)

AllenG
AllenG

Reputation: 8190

Try adding your word boundry:

(-?([0-9]*\.[0-9]+|[0-9]+)\b)|(center)|(top)|(left)|(bottom)|(right) 

Upvotes: 0

Mark Byers
Mark Byers

Reputation: 838306

The regular expression matches because it found two digits not followed by "deg": The 36 is followed by 0 and that isn't "deg". The [0-9]* is usually greedy but if this causes the match to fail it will try alternatives matching fewer digits.

You can change the negative lookahead to this:

(?!deg|[0-9.])

Upvotes: 2

Related Questions