简体   繁体   中英

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.

Ie 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 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

You could use an alternation:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM