I need to check if the string
contains exactly 5 characters. If so I need to return true.
string name = "Perry";
I need to only use regex here.
var re = Regex.Match(name, "^.{1,5}$");
However, this returns true if the characters are in range 1 and 5. What I expect is for the result to return true only if it contains 5 characters. how can i do this ?
^.{1,5}$
mean your string can contains from 1 to 5 char. You can use ^.{5}$
for exactly 5 chars.
Regex.IsMatch("Perry", "^.{5}$");
I guess, you can simply do this:
string name = "Perry";
if(name.Length == 5)
.{5}
will match any character of 5 length. If you only want alphanumeric characters, then can use:
^[A-Za-z0-9]{5}$
What I expect is for the result to return true only if it contains 5 characters.
But which characters are valid? Is \\n
a valid character here?
If yes; then use a regex like ^[\\S\\s]{5}$
instead
^ asserts position at start of the string
[\S\s] matches any whitespace or non-whitespace character
{5} matches exactly 5 times
$ asserts position at the end of the string
Some other options those may make sense are:
. matches any character (except for line terminators) ([\\r\\f\\v] are also valid here) \\w matches any word character (equal to [a-zA-Z0-9_]) -> recommended \\S matches any non-whitespace character (equal to [^\\r\\n\\t\\f\\v ])
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.