正则表达式以匹配Google地图网址

use*_*997 -1 php regex

我是新的正则表达式我想比较必须匹配特定Url的url字符串,如果匹配则返回true否则返回true.例如,我的网址是http(s):// map.google.{any letter here}/maps

必须严格匹配上述表达式,请提供帮助

Rob*_*bie 5

更新(包括评论请求)

这应该工作:

^(http(s?)://)?maps\.google(\.|/).*/maps/.*$
Run Code Online (Sandbox Code Playgroud)

请注意,现在这将允许文字中的一个.或一个/,google因此以下两个都匹配:

maps.google/co.ke/maps/anything
maps.google.co.ke/maps/anything
Run Code Online (Sandbox Code Playgroud)

以下是来自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)
"
Run Code Online (Sandbox Code Playgroud)

这是你在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';
}
Run Code Online (Sandbox Code Playgroud)

这就是你在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
}
Run Code Online (Sandbox Code Playgroud)

另外,你注意到你的谷歌网址是map.google- 不应该maps.google吗?我根据您在下面的评论中使用的输入在我的答案中假设了这一点.