0

I want to find the text occurring between the last occurrence of the word "to" in a sentence and another word "Mary".

So, for the sentence

"I went on Friday morning to bed, then to arrive for that thing and then to beloved Mary"

My regex should match the string "beloved".

I've tried the following code:

var str = "I went on Friday morning to  bed, then to arrive for that 
thing and then to beloved Mary";
var r = /to\b(.*)Mary/g
var match = r.exec(str);
console.log(match);

And am using the global flag as I want to match all occurrences of the word "to". I'm expecting it to return an array of strings, with one of them being the string "beloved" but the output I get is:

["to bed, then to arrive for that thing and then to beloved Mary", " bed, then to arrive for that thing and then to beloved "]

Jsbin here:

http://jsbin.com/puyijo/edit?js,console

Any suggestions?

EDIT: The word "Mary" is not necessarily at the very end of the string.

3
  • Is Mary at end of string ? Commented May 3, 2017 at 12:55
  • Not necessarily - question edited Commented May 3, 2017 at 12:57
  • /.*to\b *(.*?) *\bMary/g Commented May 3, 2017 at 12:58

4 Answers 4

2

Since you're looking for the last occurrence of to, you can greedily consume any other instances of to with .*:

 /.*to\b(.*)Mary/

With the requirement you've described, the /g is not necessary, since there can only be one "last occurrence of to"

Sign up to request clarification or add additional context in comments.

Comments

0

Regex parser is greedy by default, so it will first try starting from the first occurrence of to.

You need to discard all the previous characters using .*:

/.*to\b *(.*?) *\bMary/g

Comments

0

Try this pattern /(to)(?!.*\1)(.*)Mary/g

  1. '(to)(?!.*\1)' its matching the last to
  2. (.*) is find the text between to and Mary

Demo Regex

var str = "I went on Friday morning to  bed, then to arrive for that thing and then to beloved Mary";
var r = /(to)(?!.*\1)(.*)Mary/g;
var match = r.exec(str);
console.log(match[2]);

Comments

0

You need to match something before the actual to-Mary sequence:

var r = /.+to(.+)Mary/

You also do not use the group flag.

Then your matching group is the 1st group: match[1].

Note that if you might want to trim the result, or add some other chars outside the group in the regex, e.g. \s,;\. to not capture those, if you only want the word/s in between.

Cheers.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.