c# - 如何为以下条件创建正则表达式?

标签 c# regex

我正在为以下条件创建正则表达式

字符串可以包含任何字母、数字以及 ' 和 ? 字符串应以字母或数字开头

例如:

adsfj
asfj's
jfkd'sdf?
df
ds?
afjdk?

全部有效

我使用C# 2.0

我尝试过这样的事情

  ^[a-zA-Z0-9]+[']\*[a-zA-Z0-9]\*[?]\*[a-zA-Z0-9]\*$

这并没有解决问题......有什么想法......?

最佳答案

它比你做的要简单:^[a-zA-Z\d][a-zA-Z\d'?]*$

^            # Start of string anchor.
[a-zA-Z\d]   # First character is a letter or a digit.
[a-zA-Z\d'?] # Subsequent characters are letters, digits, apostrophes or question marks...
*            # ...repeated any number of times.
$            # Until the end of the string.

如果您允许使用下划线与其他字符,则可以将其简化为:^\w[\w'?]*$

关于c# - 如何为以下条件创建正则表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2219995/

相关文章:

c# - 为什么我的C#程序无法识别长度?

c# - 如何在 MVC 中创建 List<> 隐藏字段并将其提交给 Controller

c# - 如何通过 ServiceBehavior 配置启用 WCF 帮助页面?

regex - Apache mod_rewrite .htaccess - 类似链接

javascript - 需要 RegEx for URI 模板 (RFC 6570)

regex - "infinite"URL 的正则表达式

php - 匹配正则表达式中的整个字符串

c# - 使用 Awesomium(与 WPF)有什么缺点?

c# - 如何更新 Entity Framework 中的多对多表

JavaScript 分割 window.location.hash