tags:

views:

81

answers:

5

I'm 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've tried a few variants to match the negative numbers, but they just stop anything from being matched:

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

What am I supposed to do here? - isn't a special character in regex, is it?

A: 

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

webdestroya
That works for the first two lines, but the last one still isn't being matched.
Rosarch
Try escaping it? `\-` or something perhaps?
webdestroya
Nope, still fails: http://www.rubular.com/r/QomzrS9lyx
Rosarch
@Rosarch - Your regex works fine, you just need to add a space after the `\w` block - as your 3rd line has 2 spaces in it.
webdestroya
A: 

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

Your problem comes from v -12.1892 -53.4267 -276.4055 containing 2 spaces in between v and -12.18.... Your regex only matches one.

Try this regex instead:

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

Although your regex could be simplified to (not sure exactly what you want to match and capture though):

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

See it on http://rubular.com/r/D86njdYzJF

NullUserException
That is very correct. Nice catch.
Rosarch
And the downvote is because...?
NullUserException
idk. No downvote from me.
Rosarch
A: 

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

Soldier.moth
You don't need to escape `-` inside a character class if it is the first character after the `[` - for example, `[-0-9]` will accept negative numbers because the first `-` is read literally.
Echelon
Care to explain the downvote?
Soldier.moth
A: 

The reason why it isn't matching is because your third line has TWO spaces between the v and -12.1892. Try this:

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

Here is the jsfiddle to test it: http://jsfiddle.net/xewys/

Kranu
Anyone care to explain why this is downvoted?
Kranu
Probably because it has an upvote. Every answer for this question that has an upvote also has a downvote.
Soldier.moth
Oh so it's like a new trend to have a 0 total vote xP
Kranu
A: 

Rosarch, you haven't been all that specific in stating your requirements - the most basic regex I could think of to match your sample data was "(\S+\s+)+" but that might not be suitable for you - it seems too generic. Let me know what you're trying to achieve and I'll give you the regex,

Echelon