Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of the single quotes in this regex expression?

I've inherited some C# code with the following regular expression

Regex(@"^[a-zA-Z''-'\s]{1,40}$")

I understand this string except for the role of the single quotes. I've searched all over but can't seem to find an explanation. Any ideas?

like image 943
Michael Repucci Avatar asked Feb 19 '23 14:02

Michael Repucci


1 Answers

From what I can tell, the expression is redundant.

It matches a-z or A-Z, or the ' character, or anything between ' and ' (which of course is only the ' character again, or any whitespace.

I've tested this using RegexPal and it doesn't appear to match anything but these characters. Perhaps the sequence was generated by code, or it used to match a wider range of characters in an earlier version?

UPDATE: From your comments (matching a name), I'm gonna go ahead and guess the author thought (s)he was escaping a hyphen by putting it in quotes, and wasn't the most stellar software tester. What they probably meant was:

Regex(@"^[a-zA-Z'\-\s]{1,40}$") //Escaped the hyphen

Which could also be written as:

Regex(@"^[a-zA-Z'\s-]{1,40}$") //Put the hyphen at the end where it's not ambiguous
like image 95
Mike Christensen Avatar answered May 01 '23 08:05

Mike Christensen