iCart iCart - 2 years ago 163
Javascript Question

How to make a regex part "backwards lazy"?

Apologies for the terrible title, i don't know how to express this in short form.

I have a string containing html (text, some

span
s and some
<br>
s).
What i'm trying to achieve is to find the first
span
with a class ending "-focused". For added fun, the
span
s have line returns in the
title
attribute. However they do have a fixed structure and i can rearrange them if needed.
This is what i have so far:

<span[\s\S]*?class=".*-focused"[\s\S]*?>[\s\S]*?<\/span>


But i get a match from the start of the first span to the end of the matching span.
Here's a regex101 link to illustrate (contains example text)

https://regex101.com/r/W7YDU5/2

I tried playing with positive/negative lookaheads and capturing/non-capturing groups, but i'm more confused than anything at this point.

Psi Psi
Answer Source

You should avoid using the first [\s\S] here. To get what you need, you may want to proceed within the same opening tag. That is implicitly done when matching everything except >:

<span[^>]*?class=".*-focused"[^>]*?>[\s\S]*?<\/span>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download