[英]How do I use a string in both regex Match and IsMatch?
Assume I have string 假设我有字符串
var rgx = @"^[a-zA-Z0-9]\d{2}[a-zA-Z0-9](-\d{3}){2}[A-Za-z0-9]$";
I want to match it with a string, so I use 我想用一个字符串来匹配它,所以我用
var m = Regex.Match(mystring, rgx);
if (m.Success)
{
\\do something
}
Then somewhere else in the code I want use rgx
as a Regex to perform a IsMatch
operation, so I basically create a new variable 然后在代码中的其他地方,我想使用rgx
作为Regex来执行IsMatch
操作,因此我基本上创建了一个新变量
Regex rgx2 = new Regex(@"^[a-zA-Z0-9]\d{2}[a-zA-Z0-9](-\d{3}){2}[A-Za-z0-9]$");
Then use something like 然后使用类似
rgx2.IsMatch(somestring)
But this does not look right...how can I do this more efficiently? 但这看起来不正确...我如何才能更有效地做到这一点?
Try this simple approach 试试这个简单的方法
declare the string as regex 将字符串声明为正则表达式
Regex rgx = new Regex(@"^[a-zA-Z0-9]\d{2}[a-zA-Z0-9](-\d{3}){2}[A-Za-z0-9]$");
Then do your Match as 然后做你的比赛
var m = Regex.Match(mystring, rgx.ToString());
if (m.Success)
{
\\do something
}
And your IsMatch check as 和您的IsMatch检查为
rgx.IsMatch(somestring)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.