是正则表达的新手 我想比较必须与特定Url匹配的url字符串,如果匹配则返回true,否则返回true。例如我的网址是http(s)://map.google.{ any letter here }/maps
必须与该格式的上述表达式严格匹配,请帮助
答案 0 :(得分:5)
更新(包括评论请求)
这应该有效:
^(http(s?)://)?maps\.google(\.|/).*/maps/.*$
请注意,现在允许在文字.
之后使用/
或google
,因此以下两项都匹配:
maps.google/co.ke/maps/anything
maps.google.co.ke/maps/anything
以下是来自RegexBuddy的注释,以帮助您理解
@"
^ # Assert position at the beginning of the string
( # Match the regular expression below and capture its match into backreference number 1
http # Match the characters “http” literally
( # Match the regular expression below and capture its match into backreference number 2
s # Match the character “s” literally
? # Between zero and one times, as many times as possible, giving back as needed (greedy)
)
:// # Match the characters “://” literally
)? # Between zero and one times, as many times as possible, giving back as needed (greedy)
maps # Match the characters “maps” literally
\. # Match the character “.” literally
google # Match the characters “google” literally
( # Match the regular expression below and capture its match into backreference number 3
# Match either the regular expression below (attempting the next alternative only if this one fails)
\. # Match the character “.” literally
| # Or match regular expression number 2 below (the entire group fails if this one fails to match)
/ # Match the character “/” literally
)
. # Match any single character that is not a line break character
* # Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
/maps/ # Match the characters “/maps/” literally
. # Match any single character that is not a line break character
* # Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
$ # Assert position at the end of the string (or before the line break at the end of the string, if any)
"
这就是你在php中使用它的方式:
$subject = 'maps.google/co.ke/maps/anything';
if (preg_match('%^(http(s?)://)?maps\.google(\.|/).*/maps/.*$%', $subject)) {
echo 'Successful match';
} else {
echo 'Match attempt failed';
}
这就是你在C#中使用它的方式:
var subjectString = "maps.google/co.ke/maps/anything";
try {
if (Regex.IsMatch(subjectString, @"^(http(s?)://)?maps\.google(\.|/).*/maps/.*$")) {
// Successful match
} else {
// Match attempt failed
}
} catch (ArgumentException ex) {
// Syntax error in the regular expression
}
另外,您是否注意到您的Google网址为map.google
- 不应该是maps.google
?我根据您在下面的评论中使用的输入在我的答案中假设了这一点。