[英]How do I use a string in both regex Match and IsMatch?
假設我有字符串
var rgx = @"^[a-zA-Z0-9]\d{2}[a-zA-Z0-9](-\d{3}){2}[A-Za-z0-9]$";
我想用一個字符串來匹配它,所以我用
var m = Regex.Match(mystring, rgx);
if (m.Success)
{
\\do something
}
然后在代碼中的其他地方,我想使用rgx
作為Regex來執行IsMatch
操作,因此我基本上創建了一個新變量
Regex rgx2 = new Regex(@"^[a-zA-Z0-9]\d{2}[a-zA-Z0-9](-\d{3}){2}[A-Za-z0-9]$");
然后使用類似
rgx2.IsMatch(somestring)
但這看起來不正確...我如何才能更有效地做到這一點?
試試這個簡單的方法
將字符串聲明為正則表達式
Regex rgx = new Regex(@"^[a-zA-Z0-9]\d{2}[a-zA-Z0-9](-\d{3}){2}[A-Za-z0-9]$");
然后做你的比賽
var m = Regex.Match(mystring, rgx.ToString());
if (m.Success)
{
\\do something
}
和您的IsMatch檢查為
rgx.IsMatch(somestring)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.