Demis
Demis

Reputation: 197

Is there a negative regular expression in Python (negation)?

Let's say that I want to make a RE that describes all integers. By definition the expression is:

(+|-)?[0-9]+

But the definition also matches these numbers : +0, -0, 0045

The 0045 occasion can probably be solved using a lookback expression but how can I excusively exclude the +0 and -0 strings from the RE. I thought the syntax for this was ^(+0|-0) but that's probably a RE syntax for an other framework not Pythons'.

Upvotes: 1

Views: 246

Answers (1)

Heiko Oberdiek
Heiko Oberdiek

Reputation: 1708

Then the case of zero can be handled separately. Regular expression for zero or non-zero numbers:

0|[+-]?[1-9][0-9]*

The assumptions were:

  • no superfluous heading zeroes.
  • no sign before zero
  • superfluous plus sign allowed before non-zero numbers.

Outside a character group (with square brackets), the symbol ^ means the start of the string or line depending on the flag setting of re.MULTILINE.

Upvotes: 3

Related Questions