RegEx check if string contains certain value
I need some help with writing a regex validation to check for a specific value here is what I have but it don't work
Regex exists = new Regex(@"MyWebPage.aspx");
Match m = exists.Match(pageUrl);
if(m)
{
//perfor开发者_如何学JAVAm some action
}
So I basically want to know when variable pageUrl will contains value MyWebPage.aspx also if possible to combine this check to cover several cases for instance MyWebPage.aspx, MyWebPage2.aspx, MyWebPage3.aspx
Thanks!
try this
"MyWebPage\d*\.aspx$"
This will allow for any pages called MyWebPage#.aspx where # is 1 or more numbers.
if (Regex.Match(url, "MyWebPage[^/]*?\\.aspx")) ....
This will match any form of MyWebPageXXX.aspx (where XXX is zero or more characters). It will not match MyWebPage/test.aspx however
That RegEx should work in the case that MyWebPage.aspx is in your pageUrl, albeit by accident. You really need to replace the dot (.) with \.
to escape it.
Regex exists = new Regex(@"MyWebPage\.aspx");
If you want to optionally match a single number after the MyWebPage bit, then look for the (optional) presence of \d:
Regex exists = new Regex(@"MyWebPage\d?\.aspx");
I won't post a regex, as others have good ones going, but one thing that may be an issue is character case. Regexs are, by default, case-sensitive. The Regex class does have a static overload of the Match
function (as well as of Matches
and IsMatch
) which takes a RegexOptions
parameter allowing you to specify if you want to ignore case.
For example, I don't know how you are getting your pageUrl
variable but depending on how the user typed the URL in their browser, you may get different casings, which could cause your Regex to not find a match.
精彩评论