JavaScript Regex: Match "-" only if a digit is followed by "-", but not match when there is only single "-"

I want to match the trailing hyphen, but using the expression [0-9]|-$ matches even if the string contains only one hyphen. How can I correct it?

Existing behavior

  1. - #match (incorrectly working for me)
  2. -5- #matching trailing hyphen only (correctly working for me)

Expected behavior

  1. - #shouldn't match
  2. 5- #should match trailing hyphen (only "-" not whole "5-" )

Upvotes: 1

Views: 163

Answers (1)

anubhava
anubhava

Reputation: 786291

You can use lookbehind in Javascript to assert presence of a digit behind a hyphen using this regex:

/(?<=[0-9])-/g

RegEx Demo

Upvotes: 2

Related Questions