Match image tags with regEx
I am having problems with this regex:
<img(.+)src="_image/([0-9]*)/(.+)/>
Global and case sensitive flags are enabled.
The problem is that it also captures image n (see line below), but I want it to only match image tags in the line.
<p>Image 1:<img width="199" src="_image/12/label" alt=""/> Image 2: <img width="199" src="_image/12/label" alt=""/><img width="199" src="_image/12/label" alt=""/></p>
This works if I put a newline before the image n :)
Can anyone point me to what I am doing wrong?
Thanks in advance bob
If I interpret your regex correctly, it looks like after the directory name in the first group and the file path in the second group?
<IMG.*?SRC="/_image/(\d+?)/([^"]*?)".*?/>
Don't forget to use the CaseInsensitive regex options, which wrap the regex with (? I: [regex])
In the second group, you parse everything that does not close, "right now you are looking for all the characters, in fact you do not need to search for all the characters, you want everything that is not a final quote in the line.
Also, remember to close the SRC line you are missing and that the SRC attribute cannot be the last in the tag - for example, border, width, height, etc. There can also be any number of spaces after the closing of the last attribute and the end of the / "> tag
In this regex, your first match group will contain the name of the subdirectory, and the second match group will contain everything after the / subdirectory - including nested subdirectories. If you have nested subdirectories, you may need to expand this value a little:
<IMG.*?SRC="/_image/((\d+?)/)+?([^"]*?)".*?/>
In this case, each of the leading groups will hold each of the nested directory names, and the last group will contain the filename.
a source to share
Regexes are fundamentally bad at parsing HTML (see Can you give some examples of why it is difficult to parse XML and HTML with regex? For what). You need an HTML parser. See Can you give an example of parsing HTML with your favorite parser? for examples using various parsers.
a source to share
You are using the greedy quantifier (+) without much restriction. The greedy quantifier tells the regex engine: "Capture every character that comes up and only backs off to complete the regex." This means that it will receive "image / nnnnnn / something /" from the first character sequence.
a source to share