Search code examples
regexlanguage-agnosticregex-lookarounds

Regex to match character if not between digits


I need to match a character to split a big string, let's say -, but not if it's between two digits

In a-b it should match -

In a-4 it should match -

In 3-a it should match -

In 3-4 it should not match

I've tried negative lookahead and lookbehind, but I've only been able to come up with this (?<=\D)-(?=\D)|(?<=\d)-(?=\D)|(?<=\D)-(?=\d)

Is there a simpler way to specify this pattern?

Edit: using regex conditionals I think I can use (?(?<=\D)-|-(?=\D))


Solution

  • Another option is to use an alternation to match a - when on the left is not a digit or match a - when on the right is not a digit:

    (?<!\d)-|-(?!\d)
    
    • (?<!\d)- Negative lookbehind, assert what is on the left is not a digit and match -
    • | or
    • -(?!\d) Match - and assert what is on the right is not a digit using a negative lookahead

    Regex demo