Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Assuming that the link starts or ends either with a space or at beginnd/end of line (or inside an existing <code>A</code> tag) I came up with the following code, which also includes some sample texts:</p> <pre><code>string regexPattern = "((?:&lt;a (?:.*?)href=\")|^|\\s)((?:http[s]?://)?(?:\\S+)(?:\\.(?:\\S+?))+?)((?:\"(?:.*?)&gt;(.*?)&lt;/a&gt;)|\\s|$)"; string[] examples = new string[] { "some text &lt;a href=\"http://www.msn.com/path/file?page=some.page&amp;subpage=9#jump\"&gt;MSN&lt;/a&gt; more text", "some text http://www.msn.com/path/file?page=some.page&amp;subpage=9#jump more text", "some text http://www.msn.com/path/file?page=some.page&amp;subpage=9#jump more text", "some text https://www.msn.com/path/file?page=some.page&amp;subpage=9#jump more text", "some text www.msn.com/path/file?page=some.page&amp;subpage=9#jump", "www.msn.com/path/file?page=some.page&amp;subpage=9#jump more text" }; Regex re = new Regex(regexPattern); foreach (string s in examples) { MatchCollection mc = re.Matches(s); foreach (Match m in mc) { string prePart = m.Groups[1].Value; string actualLink = m.Groups[2].Value; string postPart = m.Groups[3].Value; string linkText = m.Groups[4].Value; MessageBox.Show(" prePart: '" + prePart + "'\n actualLink: '" + actualLink + "'\n postPart: '" + postPart + "'\n linkText: '" + linkText + "'"); } } </code></pre> <p>As this code uses groups with numbers it should be possible to use the regular expression in JavaScript too.</p> <p>Depending on what you need to do with the existing <code>A</code> tag you need to parse the particular first group as well.</p> <p><strong>Update:</strong> Modified the regex as requested so that the link Text becomes group no. 4</p> <p><strong>Update 2:</strong> To better catch malformed links you might try this modified version:</p> <pre><code>pattern = "((?:&lt;a (?:.*?)href=\"?)|^|\\s)((?:http[s]?://)?(?:\\S+)(?:\.(?:[^&gt;\"\\s]+))+)((?:\"?(?:.*?)&gt;(.*?)&lt;/a&gt;)|\\s|$)"; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload