Edit regex to implement role (one letter at least required)

Viewed 38

I have a regex on my C# code and I want to edit it by adding constraint to deny the text if the string does not contains at least 1 letter, whatever the language is.

My regex: @"^(?!\s+$)[\p{L}\p{M}\p{N}\p{Zs}\t'.-]+$"

Any suggestions please.

1 Answers

Any Unicode letter can be matched with \p{L} (see your own pattern).

To match any chars other than a Unicode letter, in order to "get" to the letter in the string, you may use either \P{L}*. If you only have strings with no line breaks, you may simply use .* or .*?.

NOTE that this requirements also covers the requirement to have at least one non-whitespace char, so the (?!\s+$) lookahead becomes redundant (as all it does is cancelling a match if there are only whitespaces in the string).

To require some pattern to appear later in the string, you can use a lookahead:

@"^(?=\P{L}*\p{L})[\p{L}\p{M}\p{N}\p{Zs}\t'.-]+$"
// ^^^^^^^^^^^^^^^
@"^(?=.*\p{L})[\p{L}\p{M}\p{N}\p{Zs}\t'.-]+$"
// ^^^^^^^^^^^

See a .NET regex demo.

Details:

  • ^ - start of string
  • (?=\P{L}*\p{L}) - after zero or more chars other than Unicode letters, there must be one Unicode letter
  • [\p{L}\p{M}\p{N}\p{Zs}\t'.-]+ - one or more letters, diacritics, digits, horizontal whitespaces, ', . or - chars
  • $ - end of string.
Related