Home > front end >  match link inside <> if it is followed by pattern
match link inside <> if it is followed by pattern

Time:02-01

I need a pattern that will match the "next" link from strings that are either like:

<https://www.example.com/wp-json/wp/v2/media?context=embed&media_type=image&orderby=date&per_page=100&page=2>; rel="next"

or like:

<https://www.example.com/wp-json/wp/v2/media?context=embed&media_type=image&orderby=date&per_page=100&page=1>; rel="prev", <https://www.example.com/wp-json/wp/v2/media?context=embed&media_type=image&orderby=date&per_page=100&page=3>; rel="next"

I managed to match them with separate patterns. /(?<=<). ?(?=>)/ works for the first one, and /(?<=, <). ?(?=>; rel="next")/ for the second. Finding a single optimal pattern for both seems over my head though.

CodePudding user response:

The regular expression should find the URL you want.
I modified it a little bit, just to not find a > accidentally (notice [^>]):

(?<=<)[^>] (?=>; rel="next")

This matches both rel="next" URLs:

Matches:  
https://www.example.com/wp-json/wp/v2/media?context=embed&media_type=image&orderby=date&per_page=100&page=2
https://www.example.com/wp-json/wp/v2/media?context=embed&media_type=image&orderby=date&per_page=100&page=3

See example here:
https://regex101.com/r/vMgDbP/1

Which programming language are you using?
In case of PHP there is a difference using preg_match or preg_match_all. JavaScript can use the g modifier to search globally.
Things like that could be the issue.

  •  Tags:  
  • Related