繁体   English   中英

什么样的正则表达式可以允许特殊字符但拒绝只使用特殊字符的字符串?

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

我正在为可接受的名字和姓氏编写正则表达式。 目前我只想允许以下

  • 到 z
  • 从 A 到 Z
  • '
  • (-)(破折号)
  • 变音符号

我的正则表达式是@"^[a-zA-Z-'\\p{L}]*$"

虽然我想允许使用撇号和破折号,但我也不希望名称只是一个破折号,或者只是一个撇号。 为此,我在 Fluent Validator 中编写了一些额外的正则表达式来捕捉这些边缘情况,但它不会让我将它们分开。

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

这也不是很好,因为我也不想允许名称只是像 '''''' 这样的撇号或像 --------- 这样的破折号。

是否可以编写更有效的正则表达式来处理所有这些情况?

您可以为此使用否定前瞻断言

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

此外, a-zA-Z包含在\\p{L}

解释:

^          # 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.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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