Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9205207
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T23:53:55+00:00 2026-06-17T23:53:55+00:00

I have a .Net Regex expression that extracts all valid looking Urls from a

  • 0

I have a .Net Regex expression that extracts all valid looking Urls from a string. It passes all 20 of my unit tests except one: when the Url contains a questionmark. This causes the Regex engine to hang the process and wreak havoc.

I’ve spent quite a bit of time on this expression, but I’m unsure how to fix the issue. Hopefully a Regex pro out there can lend a hand! Two part question:

1) How can this regex pattern be improved so it does not hang when evaluating string “http://www.example.com/?a=1“:

Regex pattern:

(?<URL>(\s|^)((?<Scheme>[A-Za-z]{3,9})[:][/][/])?([A-Za-z0-9-]+[.])+([A-Za-z]+){2,4}(?(Scheme)|[/])(((?:[\+~%\/.\w-_]*[/]?)?\??#?(?:[\w]*))?)*(\s|$))

I would suggest using this awesome online .Net Regex testing engine: http://regexhero.net/tester/

2) What can I do in my calling code to prevent/recover from Regex engine hangups? Here’s the calling code:

        Regex linkParser = new Regex(UrlMatchRegex, RegexOptions.Compiled | RegexOptions.IgnoreCase);

        // Find matches and add them to the result
        foreach (Match m in linkParser.Matches(message))
        {
            result.Add(m.Value.Trim());
        }

I’ve spent quite a bit of time on this particular Regex pattern, and have tried at least 7 alternates I’ve found (including most from this page: http://mathiasbynens.be/demo/url-regex). I would prefer to improve on my existing pattern, rather than use an entirely different one, but I’m open to options.

Final Regex v1:

After a few revisions, with some help from below, my final regex match looks like this:

(?<URL>((?<=\s)|^)((?<Scheme>[A-Za-z]{3,9})[:][/][/])?([A-Za-z0-9-]+[.])+[A-Za-z]{2,4}(?(Scheme)|[/]?)(((?:[\+~%\/.\w-_]*[/]?)?\??#?&?(?:[\w=]*))?)*((?=\s)|$))

**Regex v2: Updated to include a set list of domains, port numbers, hashtags, but does not pull in trailing slashes

(?<URL>((?<=\b)|^)((?<Scheme>[A-Za-z]{3,9})[:][/][/])?([A-Za-z0-9-]+[.])+((?<TLD>\b(aero|asia|biz|cat|com|coop|edu|gov|info|int|jobs|mil|mobi|museum|name|net|org|pro|tel|travel|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cu|cv|cx|cy|cz|cz|de|dj|dk|dm|do|dz|ec|ee|eg|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mn|mn|mo|mp|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|nom|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ra|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw|arpa)\b))+(\/?)+((((?:[:\+~%/.\w-_\/])?[\?]?[#]?[&]?(?:[\w=]*))?)+(?=\?|\b)))

Test cases:
this is a test of #

Should not match:

like when you a/b test something
this sentence ends with a/
just a #hashtag

Should match:

sos.me extra
sos.me. extra <-- not period
sos.me, extra <-- not comma
sos.me/ extra <-- should match traililng /
sos.me/#hashtag? extra <-- not questionmark
sos.me? extra <-- not questionmark
www.sos.me? extra <-- not questionmark
sos.me/abcde extra
sos.me/abcde#hashtag extra
sos.me/abcdf/0 extra
sos.me/abcdf/0#hashtag extra
sos.me/something.aspx extra
sos.me/something.aspx#hashtag extra
http://something.com: extra <-- not colon
sos.me/something.aspx?name=value extra
sos.me/something.aspx?name=value#hashtag extra
http://something.com extra
https://something.com extra
http://something.com:80 extra
http://something.com:80/ extra <-- should match trailing /
http://something.com:80/?a=v&1=2 extra
http://something.com:80/?a=v&1=2#hashtag extra
http://something.com:80/?a=v&1=2# extra <-- should match trailing #
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-17T23:53:56+00:00Added an answer on June 17, 2026 at 11:53 pm

    QUESTION 1

    This is causing catastrophic backtracking:

    ([A-Za-z]+){2,4}
    

    And:

    [\+~%\/.\w-_]*[/]?
    

    I’m guessing you meant:

    ([A-Za-z]{2,4})
    

    And:

    [\+~%\/.\w-_]*
    

    Your regex does not currently match URLs with equal signs, which is why the catastrophic backtracking happens in the first place:

    \??#?(?:[\w]*)
    

    does not match ‘?a = 1′ because \w does not include ‘=’. You can fix this pretty easily:

    \??#?(?:[\w=%]*)
    

    (I threw ‘%’ in there too)

    Also, your regex is matching the whitespace before and after your URL. You may prefer lookarounds to \s as this will match a position before or after whitespace rather than the whitespace itself:

    (?<URL>((?<=\s)|^)((?<Scheme>[A-Za-z]{3,9})[:][/][/])?([A-Za-z0-9-]+[.])+[A-Za-z]{2,4}(?(Scheme)|[/])(((?:[\+~%\/.\w-_]*[/]?)?\??#?(?:[\w=]*))?)*((?=\s)|$))
    

    QUESTION 2

    There’s nothing you can do to detect or recover from a catastrophically backtracking regular expression. The best you could try is spinning the regex off into an independent thread and then terminating the thread after a certain timeout. Exactly how to do that would be an entirely different question, but it’s not difficult to find tutorials online for .NET.

    See:

    • Multithreaded Applications (C# and Visual Basic)
    • How can I recognize an evil regex?
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have the following regex expression on a dev machine that is running .NET
Looking for a regular expression for that validates all printable characters. The regex needs
I have a regular expression that works fine for me when used in ASP.NET
I'm trying to match a string in .NET Regex , I want the expression
As the titles says, im looking for a regex expression for .net validation controls
I am trying to create a .NET RegEx expression that will properly balance out
I am using the following regex in .NET to validate that a string contains
This is JavaScript regex. regex = /(http:\/\/[^\s]*)/g; text = I have http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd and I
I have .NET application that is hosted on IIS 6.1 It is impossible to
I have .Net service that listens on single port over TCP protocol. Clients connect

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.