Regular Expression to Get a String Between Two Strings in JavaScript

Regular expression to get a string between two strings in Javascript

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.

Regex Match all characters between two strings

For example

(?<=This is)(.*)(?=sentence)

Regexr

I used lookbehind (?<=) and look ahead (?=) so that "This is" and "sentence" is not included in the match, but this is up to your use case, you can also simply write This is(.*)sentence.

The important thing here is that you activate the "dotall" mode of your regex engine, so that the . is matching the newline. But how you do this depends on your regex engine.

The next thing is if you use .* or .*?. The first one is greedy and will match till the last "sentence" in your string, the second one is lazy and will match till the next "sentence" in your string.

Update

Regexr

This is(?s)(.*)sentence

Where the (?s) turns on the dotall modifier, making the . matching the newline characters.

Update 2:

(?<=is \()(.*?)(?=\s*\))

is matching your example "This is (a simple) sentence". See here on Regexr

Regex: match string between two strings within an Excel Visiual Basic application (VBA) function (marco, module). (regular expression)

As the VBA regex engine does not support lookbehind assertions, you can remove it and use a consuming pattern instead. It is simple in this case because you are actually only using the captured value (with M.SubMatches(0)) in your code.

So, the quick fix is

Const sPat As String = ", (.*)(?= \()"  

If you need to deal with tabs or spaces, or any whitespace, you need \s rather than a literal space:

Const sPat As String = ",\s+(.*)(?=\s\()"  

See this regex demo.

Details:

  • , - a comma
  • \s+ - one or more whitespaces
  • (.*) - Group 1: any zero or more chars other than line break chars as many as possible
  • (?=\s\() - a positive lookahead that matches a location that is immediately followed with a whitespace and ( char.

See the demo screenshot:

Sample Image

Match string in between two strings

You can use the regex

play\s*(.*?)\s*in

  1. Use the / as delimiters for regex literal syntax
  2. Use the lazy group to match minimal possible

Demo: