I'm trying to match <svg> tag with optional attribute viewBox and to extract its value. I want to match all of the following variations of <svg> tag:
<svg width="28" height="32" viewBox="0 0 28 32">
<!-- svg content must be grouped -->
</svg>
<svg viewBox="0 0 28 32">
<!-- svg content must be grouped -->
</svg>
<svg width="28" height="32" viewBox="0 0 28 32">
<!-- svg content must be grouped -->
</svg>
<svg>
<!-- svg content must be grouped -->
</svg>
<svg viewBox="0 0 28 32" width="28" height="32">
<!-- svg content must be grouped -->
</svg>
here, width and height and viewBox are optionals and value of viewBox attribute and svg content must be grouped.
the following regex works in case that viewBox is required attribute:
/<svg\b[^>]*\s*(viewBox=\"(\b[^"]*)\").*?>([\s\S]*?)<\/svg>/
please see demo

but when I make viewBox optional group, there is no matched group (note ? symbol after parentheses):
/<svg\b[^>]*\s*(viewBox=\"(\b[^"]*)\")?.*?>([\s\S]*?)<\/svg>/

At end it solved by following regex:
<svg\b[^>]*?(?:viewBox=\"(\b[^"]*)\")?>([\s\S]*?)<\/svg>
Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With