mhz
mhz

Reputation: 1029

regex matching "not anything of two characters"

This is what I am trying to do:

Text: -one oneitis -two +three+four+five -six-seven-eight -nine then eleven +twelve thirteen

I want to match:

  1. -one oneitis
  2. -two
  3. +three
  4. +four
  5. +five
  6. -six-seven-eight
  7. -nine then eleven
  8. +twleve thirteen

Basically, ignore matching '-' within words, but matching '+' if they exist, and ' -'

This is the regex I am using: /([-+][^+]+)/

I want to essentially do [^(+)&( -)]+

Or, match anything that is not '+' nor ' -' <- that is (space and minus)

Is there some way to do this?

Thanks in advance! (linking some tools http://rubular.com/)

Upvotes: 0

Views: 1081

Answers (2)

Andrew Cheong
Andrew Cheong

Reputation: 30283

Solution.

    ([-+](?:[^ ][-]|[ ][^-+]|[^ +-])+)

http://rubular.com/r/fTSm0pjvEX

Upvotes: 3

Kobi
Kobi

Reputation: 138067

One option is to split by \+|\B-: http://rubular.com/r/tC2zTWZI4v

The splits by every +, and - that are after a space (or any non alphanumeric character).

That means it will not split in some cases, for example +a b-c will not be split.

If you do want to match your words, and want to split in that case, you can try:

[+-]([^\s+]*[^+-]*)

http://rubular.com/r/TqQEAoJ2Yv

Upvotes: 1

Related Questions