英文:
How to make special regex in c#?
问题
在我的项目中,我想要实现特殊的正则表达式用于字符串匹配。
例如:我需要HypervisorName以首字母开始,然后是数字,像"hvm01"这样。
我使用了以下正则表达式:
[RegularExpression(@"^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])$", ErrorMessage = "Virtual Machine name is not formatted correctly")]
但是我仍然可以添加类似"test"的名称,但在我的情况下,我需要首字母和数字连在一起。
英文:
In my project I would like to implement special regex for string.
For ex: I need HypervisorName like "hvm01" first letters then numbers.
I used regex like below:
[RegularExpression(@"^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z]|[A-Za-z][A-Za-z0-
9\-]*[A-Za-z0-9])$", ErrorMessage = "Virtual Machine name is not formatted correctly")]
But I am still able to add name like "test" but in my case I need both together first letter then number.
答案1
得分: 1
可以将正则表达式更改为类似于 ^[a-z]{3,}\\d{2,}$ 并使用 RegexOptions.IgnoreCase 吗?
这将检查字符串开头 ^ 处是否有至少三个字母 [a-z]{3,},然后是至少两个数字 \\d{2,},最后是字符串的结尾 $。
您可以通过 {} 括号中的第二个选项限制最大字母数量,例如 [a-z]{3, 10} 表示最少 3 个字母和最多 10 个字母。
var r = new Regex("^[a-z]{3,}\\d{2,}$", RegexOptions.IgnoreCase);
匹配: hostname123
错误匹配: h1
匹配: HHH12
错误匹配: HHH 12
错误匹配: host name
错误匹配: host name123
英文:
can you change the regex to something like ^[a-z]{3,}\\d{2,}$ and use the RegexOptions.IgnoreCase?
This will check that there are minimum three letters [a-z]{3,} at the start ^ on the string followed by the minimum 2 digits \\d{2,} and the end of the string $.
You can limit max number of letters by second option in the {} brackets, like [a-z]{3, 10} means min 3 and max 10 letters
var r = new Regex("^[a-z]{3,}\\d{2,}$", RegexOptions.IgnoreCase);
matched: hostname123
wrong match: h1
matched: HHH12
wrong match: HHH 12
wrong match: host name
wrong match: host name123
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论