Home > Software engineering >  Regex match text with provided start and end
Regex match text with provided start and end

Time:03-21

I have a string (srcset data) and I need to match only the url starting with /images and ending with t2-q5.jpg

Input data:


       /images/upload/test/test/test/name-t2-q1.jpg  576w,                                 
    /images/upload/test/test/test/name-t2-q2.jpg  864w,                                 
               /images/upload/test/druckprodukte/flyer/name-t2-q3.jpg 1151w,                                 
     /images/upload/produkt/druckprodukte/flyer/name-t2-q4.jpg 1439w,                                 
                    /images/upload/produkt/druckprodukte/flyer/name-t2-q5.jpg 1725w                           

The formatting with multiple space characters is accurate as this is what I get when selecting the element from DOM. Any input on how to construct the regex?

Thanks!

CodePudding user response:

You can try

\/images.*?t2-q5\.jpg

It basically is your text for start and end (escaping espetial characters with a backslash like "." and "/") and in between .*? means any character, as many as there is but take as few as possible.

Working example: enter image description here

CodePudding user response:

Beside the escaping of special characters, there is no difficulties.

Just search for (possibly with the global flag) :

\/images\/.*t2-q5\.jpg

Playground : https://regex101.com/r/JCnmkO/1

  • Related