How to include minus sign in this regex?

I am trying to match the following three lines:

usemtl ftw kd 1.2 3.2 3.1 v -12.1892 -53.4267 -276.4055 

My regex matches the first two:

 ^(\w+) ((\S+)( \S+)*) *$ 

I tried several options to match negative numbers, but they just terminate something from the match:

 ^(\w+) (([\S-]+)( [\S-]+)*) *$ ^(\w+) (((\S|-)+)( (\S|-)+)*) *$ 

What am I supposed to do here? - not a special character in regular expression, is it?

+1
source share
5 answers

- - this is only a special character in character classes [...]

Your problem arises from v -12.1892 -53.4267 -276.4055 , containing 2 spaces between v and -12.18... Your regular expression matches only one.

Try this regex:

 ^(\w+)\s*((\S+)( \S+)*) *$ 

Although your regex can be simplified (not sure what exactly you want to combine and capture):

 ^(\w+)(\s*\S+)*$ 

Take a look at http://rubular.com/r/D86njdYzJF

+3
source

Put it first in the class: [-\S] , then it should work.

+2
source

There are two spaces between v and -12.1892, which seem to be your problem. Also to use - inside a character class, i.e. [...] you need to avoid it with \-

+1
source

The reason this does not match is because your third line has two spaces between v and -12.1892 . Try the following:

^(\w+) +(([\S]+)( [\S]+)*) *$ (the added + sign allows several spaces)

Here is jsfiddle to check it out: http://jsfiddle.net/xewys/

0
source

Rosarch, you were not so specific in your claim statement - the most basic regular expression that I could come up with to match your sample data was "(\ S + \ s +) +", but that may not suit you - this seems too general. Let me know what you are trying to achieve and I will give you a regular expression,

0
source

All Articles