Fabian Bosler
Fabian Bosler

Reputation: 2510

Match string conditional on character before and after

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

Upvotes: 3

Views: 249

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627101

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

Upvotes: 3

Toto
Toto

Reputation: 91488

You could use an alternation:

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

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

Upvotes: 3

Related Questions