C# – Getting “Unterminated [] set.” Error in C#

cregex

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

Best Answer

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.