Matching text between hyphens with regex

James Mclaren picture James Mclaren · Nov 8, 2012 · Viewed 10.2k times · Source

Currently I have this string

"RED-CURRENT_FORD-something.something"

I need to capture the word between the hypens. In this case the word CURRENT_FORD

I have the following written

\CURRENT_.*\B-\

Which returns CURRENT_FORD- which is wrong on two levels.

  1. It implies that everything between hyphens starts with CURRENT
  2. It includes the hyphen at the end.

Any more efficient way of capturing the words in between the hyphens without explicitly stating the first word?

Answer

Jason McCreary picture Jason McCreary · Nov 8, 2012

You can use the delimiters to help bound your pattern then capture what you want with parentheses.

/-([^-]+)-/

You can then trim the hyphens off.