Results 1 to 2 of 2
  1. #1
    kyleabaker is offline Member
    Join Date
    Dec 2013
    Rep Power

    Default Regex to match and return all anchor tags in a string

    I do not have the flexibility to use a html java library for this and am trying to do this purely with regex, so...

    I'm trying to write regex to take an input string and return results of each anchor tag that is found. For example, in the following string, it should return 3 results:

    This <b>is</b> a test <a href="link1.html" data-modal="sdfdsf87ds87fdsf8bds8fb">string</a> example to <a href="link2.html">parse</a> and return <a class="someclass" href="link3.html">some</a> anchor tag results.
    My expected results are:
    1. <a href="link1.html" data-modal="sdfdsf87ds87fdsf8bds8fb">string</a>
    2. <a href="link2.html">parse</a>
    3. <a class="someclass" href="link3.html">some</a>

    I'm trying to test this at Regex Tester and the problem I'm seeing is that my regex ( <a (.+)[^<]*</a> ) is selecting everything from the start of the first anchor tag to the end of the last anchor tag and I can't seem to figure out how to split these apart.

    Any suggestions so it returns each tag as a separate result in the match array?

    Thanks in advance!

  2. #2
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Northern Virginia, United States
    Rep Power

    Default Re: Regex to match and return all anchor tags in a string

    You need to specify a non-greedy modifier.

    Try this "(<a .*?</a>)"

    Last edited by jim829; 12-05-2013 at 04:43 PM. Reason: Removed inner capture group
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

Similar Threads

  1. Replace withing regex match
    By Tim99 in forum New To Java
    Replies: 4
    Last Post: 07-27-2012, 05:36 PM
  2. How to match arrayList with a String?
    By Lund01 in forum Advanced Java
    Replies: 2
    Last Post: 10-14-2010, 02:07 PM
  3. Match a word between any two HTML tags
    By mohammedsk in forum New To Java
    Replies: 7
    Last Post: 06-19-2010, 04:28 PM
  4. String match to the linkedlist element
    By jboy in forum New To Java
    Replies: 3
    Last Post: 09-06-2009, 07:02 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts