Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matching text between hyphens with regex

Tags:

regex

hyphen

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?

like image 650
James Mclaren Avatar asked Nov 08 '12 14:11

James Mclaren


People also ask

How do you match a hyphen in regex?

In regular expressions, the hyphen ("-") notation has special meaning; it indicates a range that would match any number from 0 to 9. As a result, you must escape the "-" character with a forward slash ("\") when matching the literal hyphens in a social security number.

How do you match expressions in regex?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).

What is difference [] and () in regex?

[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9. (a-z0-9) -- Explicit capture of a-z0-9 .

What does \\ mean in regex?

\\. matches the literal character . . the first backslash is interpreted as an escape character by the Emacs string reader, which combined with the second backslash, inserts a literal backslash character into the string being read. the regular expression engine receives the string \. html?\ ' .


2 Answers

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

/-([^-]+)-/

You can then trim the hyphens off.

like image 94
Jason McCreary Avatar answered Sep 23 '22 02:09

Jason McCreary


You can use these regex

(?<=-).*?(?=-)//if lookaround is supported

OR

-(.*?)-//captured in group1

.*? matches any character i.e. . 0 to many times i.e. * lazily i.e ?

(?<=-) is a zero width look behind assertion that would match for the character - before the desired match i.e .*? and (?=-) is a zero width look ahead assertion that matches for - character after matching .*?

like image 44
Anirudha Avatar answered Sep 20 '22 02:09

Anirudha