6

Is it possible to perform lazy matching from the end of a string?

Contrived Example:

let str = "It's the end of the world as we know it"
let regex = /n.+$/
str.match(regex)         //finds "nd of the world as we know it"

Simple enough, it finds 1 or more any character from the end of the string until it finds the last "n" (going backwards).

Now, however, let's say I want it to find 1 or more any character from the end of the string until it finds the first "n" (going backwards). You would think you could add the 'lazy' quantifier, like this:

let regexLazy = /n.+?$/

but the result would still be the same:

str.match(regex)         //finds "nd of the world as we know it"

Is it possible to do lazy matching when starting from the end of a string? What am I missing? Thanks!

Jeff Schuman
  • 772
  • 7
  • 12
  • In your case, `/n[^n]*$/` will do. – Wiktor Stribiżew Oct 12 '20 at 21:16
  • Another trick is to reverse the input string, do the regexp, then reverse the output. (Probably this is overkill for your simple example.) – Rick James Oct 12 '20 at 21:19
  • Yep, thank you both for the comments. I do understand that there are other ways to accomplish the same thing (regex!), but in this case it's more a curiosity as to how/why lazy matching doesn't seem to "work" when matching from the end of the string. – Jeff Schuman Oct 12 '20 at 21:22
  • But regex in these these case processes left to right. In Wiktor's solution the [^n] condition fails to match end-of-statement for the first "n", but the next "n" matches. – TonyR Oct 13 '20 at 10:58
  • (n.*)*(n.*?)$ would achieve what you are trying to achieve with lazy quantifier. But because lazy matches can be time consuming, the approach using [^n]* is better when it can be used. – TonyR Oct 14 '20 at 10:45

0 Answers0