Home > Blockchain >  regex match specific a tag in a tags
regex match specific a tag in a tags

Time:12-04

I want to get Match Result from InputString using Regex. I tried but kept failing. How can I do this? thanks in advance!

InputString

<a href="https://www.google.com" class="btn"><a href="https://www.google.com" class="btn"><a href="https://www.google.com" class="btn_next"><a href="https://www.google.com" class="btn"> 

Match Result

<a href="https://www.google.com" class="btn_next">  

Pattern I tried but fail

<a\s .*?href="(.*?)".*?class="btn_next".*?>

CodePudding user response:

Should you be using RegEx to parse HTML, probably not, see: RegEx match open tags except XHTML self-contained tags

You could do this - but probably shouldn't:

<a[^>] \bhref\s*=\s*"([^"] )"[^>] \bclass\s*=\s*"btn_next"[^>]*>

Yes, this expression can be made simpler if you absolutely control the input, this expression is written so the markup not being absolutely exactly as per your example, i.e. multiple spaces, possibility of more attributes. But does require the href attribute to come before the class attribute.

Also keep in mind you might have multiple classes in your class attribute and this expression does not deal with that.

  • Related