简体   繁体   中英

Regex to match images followed with a space in an HTML string

I'm trying to write a regex that matches any <img /> tag followed with a space, followed with some text.

In other words, I want these lines to be matched:

  • Hello <img /> world!
  • <span>Hello <img /></span> world!
  • <span>Hello <img /> </span>world!

But not those ones:

  • Hello <img />!
  • <span>Hello <img /></span>!
  • <span>Hello </span> world!
  • <span>Hello <img /></span>my world!

While I managed to match images using <img[\\w\\W]+?\\/> , I can't figure out how to match the space followed with text, especially when some closing tags are located in between...

See RegExr here .

Update #1

New update matches following tags as well like in <span>Hello <img /></span> world!

If you need to match whole line you need to see whether each line matches corresponding regex or not then try to output it using:

^(.*?<img[^>]*>(<\/?\w+[^>]*>)* +\S).*

Note: watch m flag.

Live demo

Otherwise if you are trying to match tags following a space following a non-space this is how it could be done in regex:

<img[^>]*>(<\/?\w+[^>]*>)* +(?=\S)
                             ^ constructing a positive lookahead

Live demo

Would /<img.+?\\/>(?=.* )/gi work?

http://regexr.com/3frgd

Edit

With the newer test case, here is a version for image tags immediately followed by a space with other tags optionally before it

/<img.+?\\/>(?=(<.*?>)* )/gi

http://regexr.com/3frgm

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM