Home > Net >  Regex exclude matches where last two characters of string are combination of - and number
Regex exclude matches where last two characters of string are combination of - and number

Time:03-19

Tried with [^-][^0-9]$, but this also excludes d9 or -a. I would like this to only work with -1, -2, -3 etc.

enter image description here

CodePudding user response:

You can use an NFA regex with lookbehind support like

$(?<!-[0-9])

It matches an end of string that is not immediately preceded with a - a digit.

A variation of this is

^(?!.*-[0-9]$)
^(?!.*-[0-9]$).*

If you deal with a POSIX (ERE here) regex engine, you can use

^(.*([^-].|.[^0-9])|.)$

See this regex demo. Details:

  • ^ - start of string
  • ( - start of a group:
    • .* - any zero or more chars
    • ([^-].|.[^0-9]) - either a char other than a - and then any one char, or any single char and then any char other than a digit
  • | - or
    • . - any one char
  • ) - end of the group
  • $ - end of string.
  • Related