-2

I am trying to figure out a regex pattern for the following img src tag

<img src="attachment.jpg" alt="attachment.jpg" />

I just want the img src tag here for instance the 'attachment.jpg", however is there such a pattern that can find the img src if its in different locations throughout the request, for instance like this

<img height="" weight="" src="attachment.jpg" alt="attachment.jpg" />

So within my returned pattern it would always find <img src="attachment.jpg" and then return me the "attachment.jpg" regardless of position

Broken Mind
  • 511
  • 3
  • 8
  • 22
  • Does this answer your question? [RegEx match open tags except XHTML self-contained tags](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags) – Marcin Mrugas Nov 26 '20 at 13:01

1 Answers1

0
String regex = "<img .*src=\"([^\\s]+)\"";
Pattern pttrn = Pattern.compile(regex);
String str = "<img height=\"\" weight=\"\" src=\"attachment.jpg\" alt=\"attachment.jpg\" />";
Matcher mtchr = pttrn.matcher(str);
if (mtchr.find()) {
    System.out.println(mtchr.group(1));
}
String str2 = "<img src=\"attachment.jpg\" alt=\"attachment.jpg\" />";
mtchr = pttrn.matcher(str);
if (mtchr.find()) {
    System.out.println(mtchr.group(1));
}

The above regular expression searches for <img followed by a single space, followed by zero or more characters (any characters), followed by src=" followed by one or more non-space characters and finally followed by ". The characters between the double quotes are stored in a group. Hence the contents of the group is what you wish to obtain.

Abra
  • 19,142
  • 7
  • 29
  • 41