Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to get a string between two strings in Javascript

I have found very similar posts, but I can't quite get my regular expression right here.

I am trying to write a regular expression which returns a string which is between two other strings. For example: I want to get the string which resides between the strings "cow" and "milk".

My cow always gives milk

would return

"always gives"

Here is the expression I have pieced together so far:

(?=cow).*(?=milk) 

However, this returns the string "cow always gives".

like image 218
phil Avatar asked Apr 12 '11 22:04

phil


People also ask

How do you find the string between two characters?

To get a substring between two characters:Get the index after the first occurrence of the character. Get the index of the last occurrence of the character. Use the String. slice() method to get a substring between the 2 characters.

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 \.


Video Answer


1 Answers

A lookahead (that (?= part) does not consume any input. It is a zero-width assertion (as are boundary checks and lookbehinds).

You want a regular match here, to consume the cow portion. To capture the portion in between, you use a capturing group (just put the portion of pattern you want to capture inside parenthesis):

cow(.*)milk 

No lookaheads are needed at all.

like image 175
R. Martinho Fernandes Avatar answered Sep 29 '22 14:09

R. Martinho Fernandes