![](/img/trans.png)
[英]How to Write a Regular Expression that allows only letters, numbers and special characters only i the middle never in the end
[英]How to write regular expression that matches only numbers,text,spaces and only two special characters
如何編寫僅匹配數字,文本以及僅匹配這兩個特殊字符#和-[a-zA-Z0-9#-\\ s] +的任何其他內容的正則表達式
你可以這樣一個正則表達式
^(\d|[a-z]|[A-Z]|#|-)*$
在我用於檢查C#中的正則表達式的代碼下面:
string input = @"343243-2df---ds#SFD#FD";
string pattern = @"^(\d|[a-z]|[A-Z]|#|-)*$";
Console.WriteLine(Regex.Match(input, pattern).Success);
Console.ReadLine();
另外,有關將來的參考資料,您可以訪問以下正則表達式站點: http : //www.regular-expressions.info/
我相信以下模式可以在C#中使用:
string pattern = @"^[a-zA-Z\d\s#-]*$";
我只是在C#交互中嘗試了幾個測試用例:
Regex.Match("", pattern).Success
> true
Regex.Match("asdf 2F#-#-", pattern).Success
> true
Regex.Match("asdf~asdf", pattern).Success
> false
如果您不想接受空字符串,只需將模式中的*更改為+。 另外,您沒有聲明要與問題中的空格匹配,但是示例模式確實與空白匹配。 如果您不想匹配空格,請刪除\\ s。
更新 :根據Rawling的建議進行編輯。
嘗試這個:
^([a-z]|[A-Z]|[#]|[0-9]|[-])+$
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.