简体   繁体   中英

How to make special regex in c#?

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.

can you change the regex to something like ^[az]{3,}\\\\d{2,}$ and use the RegexOptions.IgnoreCase ?

This will check that there are minimum three letters [az]{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 [az]{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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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