Denver19
Denver19

Reputation: 13

What kind of regex can allow special characters but refuse strings that only use special characters?

I am writing an regex for acceptable first names and last names. Currently I only want to allow the following

My regex is @"^[a-zA-Z-'\p{L}]*$"

Although I want to allow apostrophes and dashes, I also don't want the name to be just a dash, or just an apostrophe. So to do this, I've written some extra regexes in Fluent Validator to catch these edge cases but it won't let me split them up.

        .Matches(@"^[a-zA-Z-'\p{L}]*$")
        .Matches(@"[^-]")
        .Matches(@"[^']");

This also isn't that great since I also don't want to allow names that are just apostrophes like '''''' or just dashes like ---------.

Is there a more effective regex that can be written to handle all of these cases?

Upvotes: 1

Views: 100

Answers (1)

Tim Pietzcker
Tim Pietzcker

Reputation: 336158

You can use a negative lookahead assertion for this:

@"^(?![-']*$)[-'\p{L}]*$"

Also, a-zA-Z are included in \p{L}.

Explanation:

^          # Start of string
(?!        # Assert that it's impossible to match...
 [-']*     # a string of only dashes and apostrophes
 $         # that extends to the end of the entire string.
)          # End of lookahead.
[-'\p{L}]* # Match the allowed characters.
$          # End of string.

Upvotes: 1

Related Questions