Kaylons
Kaylons

Reputation: 3

Regular expression problem, avoid the first sign, and get the second one

I have a small problem. I try to extract some matches from a string, like this. But I don't know how to do this. Thanks

2+22 -> match1: 2; match2: 22

2-22 -> match1: 2; match2: 22

2++22 -> match1: 2; match2: +22

2+-22 -> match1: 2; match2: -22

Upvotes: 0

Views: 23

Answers (1)

xdhmoore
xdhmoore

Reputation: 9915

I don't know what language you are using, but the following seems to work for those test cases using PHP/PCRE:

(\d+)[+-]([+-]?\d+)

To break it down:

  • (\d+) match at least one digit, and capture it in group 1
  • [+-] match either a plus or minus
  • ([+-]?\d+) match either a plus or minus or nothing, followed by at least one digit. Capture the whole thing in group 2.

Upvotes: 1

Related Questions