【问题标题】:C# Regular expression - exclude underscores & spaces at beginning and end of textC# 正则表达式 - 排除文本开头和结尾的下划线和空格
【发布时间】:2021-03-06 01:59:30
【问题描述】:

我一直在努力让这个正则表达式起作用。 我希望表达式在字符串的开头或结尾包含空格时显示错误(允许中间的空格)。另外我想排除下划线和连字符。

这是我目前所拥有的。

[RegularExpression(@"^.*\s*[-_]", ErrorMessage = "string cannot begin with or end with a space, or contain a hyphen or underscore")]

这没有按预期工作,有人知道我缺少什么来让它工作吗?

【问题讨论】:

    标签: c# regex asp.net-mvc


    【解决方案1】:

    你可以使用

    [RegularExpression(@"^[^\s_-]+(?:\s+[^\s_-]+)*$", ErrorMessage = "string cannot begin with or end with a space, or contain a hyphen or underscore")]
    

    详情

    • ^ - 字符串开头
    • [^\s_-]+ - 除空格之外的一个或多个字符,_-
    • (?:\s+[^\s_-]+)* - 零个或多个重复:
      • \s+ - 一个或多个空格
      • [^\s_-]+ - 除空格以外的一个或多个字符,_-
    • $ - 字符串结束。

    请参阅regex demo

    【讨论】:

    • 感谢wiktor,这符合我的预期!非常感谢
    猜你喜欢
    • 2021-09-01
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 2015-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多