有,你可以用它來解決這個多種方法,我將回顧在幾個。
使用String.Split()
方法
你可以使用String.Split()
方法打破了一個字符串轉換成它的帶分隔符的各個組件。在這種情況下,你可以使用空格作爲分隔符來獲得個人的話:
// Get your words, removing any empty entries along the way
var words = YourTextBox.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
// Determine how many words you have here
if(words.Length != 2)
{
// Tell the user they made a horrible mistake not typing two words here
}
使用正則表達式
此外,你可以嘗試使用Regex.IsMatch()
通過正則表達式來解決這個方法:
// Check for exactly two words (and allow for beginning and trailing spaces)
if(!Regex.IsMatch(input,@"^(\s+)?\w+\s+\w+(\s+)?"))
{
// There are not two words, do something
}
表達本身可能看起來有點嚇人,但它可以被分解如下:
^ # This matches the start of your string
(\s+)? # This optionally allows for a single series of one or more whitespace characters
\w+ # This allows for one or more "word" characters that make up your first word
\s+ # Again you allow for a series of whitespace characters, you can drop the + if you just want one
\w+ # Here's your second word, nothing new here
(\s+)? # Finally allow for some trailing spaces (up to you if you want them)
「單詞」字符\w
是正則表達式中的一個特殊字符,它可以表示數字,字母或下劃線,相當於[a-zA-Z0-9_]
。
使用MVC的RegularExpressionAttribute
最後以正則表達式的優勢,因爲你正在使用MVC,你可能對你的模型本身的優勢[RegularExpressionValidation]
屬性:
[RegularExpression(@"^(\s+)?\w+\s+\w+(\s+)?", ErrorMessage = "Exactly two words are required.")]
public string YourProperty { get; set; }
這將允許你只需在您的控制器操作中調用ModelState.IsValid
以查看您的型號是否有任何錯誤:
// This will check your validation attributes like the one mentioned above
if(!ModelState.IsValid)
{
// You probably have some errors, like not exactly two words
}
什麼關於匹配「Cpl \ 3 John Smith」或「Mr.約翰史密斯?我有'@「^(\ s +)?[A-Za-z _.-] + \ s \ w + \ s \ w +(\ s +)?$」' –
您是否希望允許那些除了以前的案例或作爲一個完全獨立的集?從技術上講,這些由三個詞組成。 –
是的,除了我之前的情況。 3是最大值和最小值 –