开发者

How can I include a minus sign in this regex?

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?


- 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


Put it first in the class: [-\S]

Then it should work.


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 \-


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/


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜