3 回答

TA貢獻(xiàn)1801條經(jīng)驗(yàn) 獲得超8個(gè)贊
我相信有人可以提供更簡(jiǎn)潔的答案,但模式匹配是要走的路。
using System.Text.RegularExpressions;
string test = "32P125";
// 2 integers followed by any upper cased letter, followed by 3 integers.
Regex regex = new Regex(@"\d{2}[A-Z]\d{3}", RegexOptions.ECMAScript);
Match match = regex.Match(test);
if (match.Success)
{
//// Valid string
}
else
{
//// Invalid string
}

TA貢獻(xiàn)1835條經(jīng)驗(yàn) 獲得超7個(gè)贊
考慮到“P”必須按字面匹配——
using System;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
string st1 = "32P125";
string st2 = "N23P33";
Regex rg = new Regex(@"\d{2}P\d{3}");
// If 'P' is not to be matched literally, reeplace above line with below one
// Regex rg = new Regex(@"\d{2}[A-Za-z]\d{3}");
Console.WriteLine(rg.IsMatch(st1));
Console.WriteLine(rg.IsMatch(st2));
}
}
輸出
True
False

TA貢獻(xiàn)1786條經(jīng)驗(yàn) 獲得超11個(gè)贊
我會(huì)鼓勵(lì)使用MaskedTextProvidedover Regex。
這不僅看起來更干凈,而且更不容易出錯(cuò)。
示例代碼如下所示:
string Num = "12P123";
MaskedTextProvider prov = new MaskedTextProvider("##P###");
prov.Set(Num);
var isValid = prov.MaskFull;
if(isValid){
string result = prov.ToDisplayString();
Console.WriteLine(result);
}
- 3 回答
- 0 關(guān)注
- 200 瀏覽
添加回答
舉報(bào)