tags:

views:

65

answers:

2

I'm trying to write a regular expression that will check so a given string is a "valid" name. The name-strings are retrieved from a database and then checked to see if they contain weird chars. (Since this is for a Swedish system, I still have to include a few weird chars that are common in Swedish names. ;) )

The problem is that this fails every single string it's fed. My guess is that the regex isn't terminated correctly, and that if fails the end of a string. But I can't figure out why.

So my regex looks like follows - and I've tried both the regex strings in the example:

    public static bool NameCheck(string name)
    {
        if(name == "" || name == " " || name == null)
        {
            return false;
        }

        //Regex regex = new Regex(@"/^[a-zåäöÅÄÖáéóúýíüÁÉÓÚÝÍÜ\-\.]+([---\s][a-zåäöÅÄÖáéóúýíüÁÉÓÚÝÍÜ\-\.]+)+/i");
        Regex regex = new Regex(@"/^[a-zåäöÅÄÖáéóúýíüÁÉÓÚÝÍÜ\-\.]+([---\s][a-zåäöÅÄÖáéóúýíüÁÉÓÚÝÍÜ\-\.]+)+$/i");

        return regex.IsMatch(name);
    }

Any takers?

Note: I'm solving the problem in my system by splitting the strings before the regex check so I don't have to handle white space, but I'm curious why the regex doesn't work.

+5  A: 

C# regular expression should not use the "/" delimiters, so you should use the following syntax:

Regex regex = new Regex(@"^[a-zåäöÅÄÖáéóúýíüÁÉÓÚÝÍÜ\-\.]+([---\s][a-zåäöÅÄÖáéóúýíüÁÉÓÚÝÍÜ\-\.]+)+$",
                        RegexOptions.IgnoreCase);
Philippe Leybaert
They *must not* use them, actually. That's basically a sed/perl/Javascript thing and has nothing to do with regular expressions in general. Or in other implementations.
Joey
Well I'll be... I actually tried that at one point, but didn't include the RegexOptions.IgnoreCase at the end. Thanks!
Marcus L
+1  A: 

[a-zåäöÅÄÖáéóúýíüÁÉÓÚÝÍÜ\-\.]

So you'll never have any Bjørn-s or Łukasz-es? Considered [\w.-] and then having the regex consider what Unicode defines as alpha-numerics? \w will match [0-9] as well, but you can always check against those in a second regex.

[---\s]

Say what? What about [\s-].

Alex Brasetvik