Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match string conditional on character before and after

Tags:

python

regex

Regex is always giving me a headache. I am trying to match a pattern, where it would only match if and only if both characters before and after are not a digit. It is okay, if one of the characters is a digit.

I.e. for the string "Zeitraum vom 1. 6. -30. 6." i am trying to match the dash (-), however the pattern should not be matched for "12-3-2019" (where both characters before and after the dash are digits).

Currently I am trying exclusions, but that seems to match if neither of the characters are a digit.

[^\d]-[^\d]

Thank you

like image 690
Fabian Bosler Avatar asked Jun 29 '26 12:06

Fabian Bosler


2 Answers

You could use an alternation:

(?<!\d)-|-(?!\d)

This matching an hyphen not preceeded by digit OR not followed by digit

like image 61
Toto Avatar answered Jul 02 '26 02:07

Toto


You may use

r'-(?<!\d-(?=\d))'

See the regex demo

It matches a - that is not preceded with a digit and - that is immediately followed with a digit.

Note that the (?=\d) lookahead is required rather than a simple \d because (?<!\d-\d) after - would be able to fail the match when backtracking.

Details

  • - - a hyphen
  • (?<! - start of a negative lookbehind: fail the match if, immediately to the left of the current location, there is
    • \d - a digit
    • - - a hyphen
    • (?=\d) - followed with \d
  • ) - end of the lookbehind
like image 29
Wiktor Stribiżew Avatar answered Jul 02 '26 01:07

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!