Solution 1 :

you can use ? at end of group for optional group patterns:

its work fine: /(<imgs)[^>]*(src=S+)[^>]*(salt=["|'].*?["|'])?[^>]*(/?>)/gm

and here the live link you can check demo: https://regex101.com/r/u2uWGX/1

enter image description here

enter image description here

Solution 2 :

If you have a set of img elements in your HTML. You can also get the src and alt value by looping a HTMLCollection.

Demo :

const imgCollection = document.getElementsByTagName('img');

for (let item of imgCollection) {
  console.log('src :', item.src)
  console.log('alt :', item.alt)
}
<img src="https://example.com/image" alt="example1">
<img src="https://example.com/image">

Problem :

I need to get from all the images the src and alt of the html code. I managed to get it but I have the following problem:

  • If the image has no alt, it does not detect me the image. In these cases I need to get only the src.

The following code works with problem:
https://regex101.com/r/3Vlkql/1

(<imgs)[^>]*(src=S+)[^>]*(salt=["|'].*?["|'])[^>]*(/?>)

Substitution:

$1$2$3$4

Result:

<img src="https://example.com/image" alt="example1">

Problem: My regex only detect if have src and alt. But if not have alt, the regex not detect me. How can I do with regex to get both?

This not match with regex:

<img src="https://example.com/image">
  • src & alt
  • only src

I dont have problem if i need to use 2 regex to get my purpose.

Comments

Comment posted by htmlparsing.com/php

Don’t use regular expressions to parse HTML. Use a proper HTML parsing module.

Comment posted by Jessika

This regex:]*balt=)[^>]*?> Match images that not have alt, but how can i group to get only for this images that not contain alt –

Comment posted by Andy Lester

You are starting to discover why you don’t want to parse HTML with regexes.

Comment posted by this with regex

Have you watched the steps counter in regex101? This pattern already looks laborious. What if

Comment posted by example.com

But not work with: ]*balt=)[^>]*?> Match images that not have alt, but how can i group to get only for this images that not contain alt

Comment posted by Mohamad Ahmadi

its work with

Comment posted by Mohamad Ahmadi

use this one

Comment posted by regex101.com/r/qeNPvz/1

Can you check why dont work?

By