0

I'm trying to find an elegant way for matching negative and positive numbers at the same time, but not to capture the + sign while capturing the - sign.

So I have something like:

re.findall("([+-] \d+)x", "6x2 + 4x + 5 - 2x2 - 7x + 4 + 87x - 100x")

This gives me all multipliers for x, both positive and negative (great!). I would like the negative numbers to be - 2, for example, but not return the plus sign for positive numbers (4 instead of + 4). I failed with ?: option, maybe I just used it incorrectly.

bunji
  • 5,063
  • 1
  • 17
  • 36

1 Answers1

0

You could make use of an alternation and a positive and lookahead and lookbehind:

(?<=\+) \d+(?=x)|- \d+(?=x)

print(re.findall("(?<=\+) \d+(?=x)|- \d+(?=x)", "6x2 + 4x + 5 - 2x2 - 7x + 4 + 87x - 100x"))
# [' 4', '- 2', '- 7', ' 87', '- 100']

Regex demo | Python demo

Explanation

  • (?<=\+) \d+(?=x) Positive lookbehind to assert what is on the left is a +, then match a space followed by one or more digits. Use a positive lookahead to assert what is on the right side is an x
  • | Or
  • - \d+(?=x) Match -, a space and one or more digits. Then use a positive lookahead to assert what is on the right is an x

If you don't want to include the space before the match without the + you could remove it before the digit and add it to the positive lookbehind:

(?<=\+ )\d+(?=x)|- \d+(?=x)

The fourth bird
  • 154,723
  • 16
  • 55
  • 70