I need a regex pattern for finding web page links in HTML.

For example

  • <a href="https://www.google.com/search?q=elisp+regex+lookaround" ....></a>

I can use (?<=href=\").+?(?=\") | (?<=href=\').+?(?=\') in Python to get the value of href.

But that involves positive lookbehind assertions (?<=...) and positive lookahead assertions (?=...) which I didn't find in elisp Regular Expressions.

  • 1
    Comparing with your Python approach you would just search for href=\(["']\)\(.+?\)\1 and use the second group \2. But the best way depends on the application. So please give a bit more background to avoid XY-problems.
    – Tobias
    Commented Jan 23, 2020 at 11:45
  • There is no doubt existing Elisp code for various HTML modes. There you will likely already find useful regexps for such things. That could be one place to start. See nxhtml.el, for example. There is also nxml.el.
    – Drew
    Commented Jan 23, 2020 at 17:06
  • @Tobias Thank you for your advice, but my intention to give that Python regex is to show I have thought over this problem. I think I have showed my original purpose rather than hide it like what X-Y problems do.
    – Ynjxsjmh
    Commented Jan 24, 2020 at 6:58
  • @Ynjxsjmh I think the suggestion is that maybe you don’t “need” a regular expression so much as a way to find these values or extract them or move to them. Keep in mind that applying regular expressions to html is I notoriously impossible in general and that there href might in general contain things like no quotes or single quotes or &apos; type escape codes. But maybe you really do need one. Commented Jan 24, 2020 at 23:03
  • For anyone who is trying to use the regex in the first comment, here is the escaped format when using searches within Emacs and to test the code with re-builder: "href=\\([\"']\\)\\(.+?\\)\\1"
    – lawlist
    Commented Dec 8, 2021 at 20:10


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.