Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting "Unterminated [] set." Error in C#

Tags:

c#

regex

I am working with following regex in C#

Regex find = new Regex("[,\"]url(?<Url>[^\\]+)\\u0026");

and getting this error:

"System.ArgumentException: parsing "[,"]url([^\]+)\u0026" - Unterminated [] set.

I'm kind of new to regular expressions so correct me if I'm wrong. The regular expression is supposed to extract urls from text matching like:

,url=http://domain.com\u0026

"url=http://hello.com\u0026

like image 735
tunafish24 Avatar asked Sep 08 '11 07:09

tunafish24


2 Answers

You need to use a verbatim string:

Regex find = new Regex(@"[,""]url(?<Url>[^\\]+)\\u0026");

Edit: However, I'd change the regex to

Regex find = new Regex(@"(?<=[,""]url=)[^\\]+(?=\\u0026)");

Then the entire match is the URL itself. No need for a capturing sub-group.

like image 182
Tim Pietzcker Avatar answered Nov 04 '22 00:11

Tim Pietzcker


You're escaping one of the brackets with \] which means you have an unterminated [.

This cheat sheet is great for .NET regexs, I have it printed out on my desk. Totally recommend it! To match \ you want \\.

Oh yeah, missed the lack of verbatim without the first edit. Go for Tim's suggestion I'd say.

One other online tool which is really handy for quick testing is Derek Slager's online tool.

like image 27
Andrew Barrett Avatar answered Nov 04 '22 02:11

Andrew Barrett