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
You could use an alternation:
(?<!\d)-|-(?!\d)
This matching an hyphen not preceeded by digit OR not followed by digit
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 lookbehindIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With