![](/img/trans.png)
[英]Csharp: Find & Replace string match between specific characters || in a string using Regex
[英]Regex counting string characters using Match
我需要檢查string
是否恰好包含5個字符。 如果是這樣,我需要返回true。
string name = "Perry";
我只需要在這里使用正則表達式。
var re = Regex.Match(name, "^.{1,5}$");
但是,如果字符在1和5范圍內,則返回true。我期望只有包含5個字符的結果才返回true。 我怎樣才能做到這一點 ?
^.{1,5}$
表示您的字符串可以包含1到5個字符。 您可以使用^.{5}$
恰好5個字符。
Regex.IsMatch("Perry", "^.{5}$");
我想,您可以簡單地做到這一點:
string name = "Perry";
if(name.Length == 5)
.{5}
將匹配5個長度的任何字符。 如果只需要字母數字字符,則可以使用:
^[A-Za-z0-9]{5}$
我期望的是結果僅包含5個字符時才返回true。
但是哪些字符有效? \\n
這里是有效字符嗎?
如是; 然后使用^[\\S\\s]{5}$
類的正則表達式代替
^ 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
可能有意義的其他一些選擇是:
. 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 ])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.