Home > Software design >  Regex - match behind an optional character
Regex - match behind an optional character

Time:03-12

I want to match a string that has more than 3 characters and combine with positive look behind an optional character (/). From the input:

100/ABC-12345 10
ABCD
ZZZ

I need to retrieve:

ABC-12345 10
ABCD

I can match them separately but cannot combine them. See my current regex:

(?<=\/).*

CodePudding user response:

You may use:

(?<=/|^)\w[\w-]{3,}

Updated Regex Demo

Positive lookbehind (?<=/|^) asserts presence of / or start of line behind current position and \w[\w-]{3,} matches at least 4 of word or hyphen characters where first character must be a word character.

CodePudding user response:

Try this:

/?[\w-]{4,}

See live demo.

This matches a slash optionally, then at least 4 of word chars or dashes.

  • Related