DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone >

.NET 4.5 Baby Steps, Part 7: Regular Expression Timeouts

Robert Maclean user avatar by
Robert Maclean
·
May. 18, 12 · · Interview
Like (0)
Save
Tweet
3.21K Views

Join the DZone community and get the full member experience.

Join For Free

introduction

while the regular expression passing in .net is damn fast, there are times where it can take too long for your needs. until now there hasn’t been much you can do but wait. in .net 4.5 we get the ability to timeout regular expressions if they took too long.

problem

so lets look at a really silly example to start off with, checking a string fifty million characters (where only one is different) against regular expression which is looking for fifty million letters. as i said it is silly, but to get a truly slow reg ex is pretty hard.

static regex match = new regex(@"\w{50000000}", regexoptions.none);
static void main(string[] args)
{
    var sw = stopwatch.startnew();
    console.writeline(match.ismatch(string.empty.padright(49999999, 'a') + "!"));
    sw.stop();
    console.writeline(sw.elapsed);
    console.readline();
}

this 13.5secs on my machine!

solution

image

all we need to do to take advantage of the new timeouts is modify the constructor of the regex, by adding a third parameter.

static regex match = new regex(@"\w{50 000 000}", regexoptions.none, timespan.fromseconds(5));

now after five seconds a regexmatchtimeoutexception is raised.

attachment size
regex timeout demo 32.73 kb
Timeout (computing)

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • After COVID, Developers Really Are the New Kingmakers
  • Autowiring in Spring
  • Challenges to Designing Data Pipelines at Scale
  • Why Is Software Integration Important for Business?

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo