-1

I need a regex to verify if the textarea has one of the following matches:

[img]https://example.com/image.jpg[/img]
[img=https://example.com/image.jpg]

This is what I've been trying so far, but it doesn't work, sadly...

/\[img(?=|\])(https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*))(?\])(?\[\/img\])/gi

Thank you.

Ultraviolet
  • 31
  • 1
  • 6
  • This will not MATCH anything: (?=|\]) It will only LOOK AHEAD which doesn't 'move the match cursor'. – Poul Bak Mar 08 '20 at 06:47

1 Answers1

-1

You can use this- ^\[img(?:\].+\[\/img\]|=.+\])$

Note: If you want to verify the link string is a valid URL, replace both .+ with a URL regex matcher, you may find one here

Explanation

  • ^\[img - This part is common both strings, this will match the [img at the start of line
  • (?:\].+\[\/img\]|=.+\])$ - This will match 2 alternatives, depending on the very first character

    • First alternative (first character is ]) - In this case \].+\[\/img\]| will be matched. This will match everything (.+) in between the opening and closing [img] tags before finally matching the closing tag itself.

    • Second alternative (first character is =) - In this case =.+\] will be matched. This grabs everything after img= and stops when ] is reached.

    finally the regex matches the end of line.

Check out the demo

Chase
  • 5,315
  • 2
  • 15
  • 41