简体   繁体   中英

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

  • a to z
  • A to Z
  • '
  • (-) (a dash symbol)
  • diacritics

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM