试图理解这个location.href.match JS RegExp部分

时间:2012-12-17 10:23:06

标签: javascript regex

我正在尝试理解这个javascript正则表达式。

有人可以给我一个关于这个正则表达式部分的解释吗?

location.href.match(/^http:\/\/(www\.)?example.com/i)

4 个答案:

答案 0 :(得分:4)

让我们分解一下:

^http:\/\/ =字符串必须以http://开头。反斜杠在那里,因为如果他们不这样做,斜杠将结束正则表达式模式。

(www\.)? =匹配www.(如果存在)(这就是问号的用途)

example.com =字符串必须跟example.com

i =不区分大小写

所以这些是可能的匹配:

  • http://example.com
  • http://www.example.com
  • http://www.EXAMPLE.COM
  • http://www.example.com/some/page/

不幸的是,正则表达式与HTTPS协议不匹配。我们可以使用与www.相同的方法使用问号:

/^http(s)?:\/\/(www\.)?example.com/i

答案 1 :(得分:2)

^           - start of line
http:       - http:
\/\/        - //
(www\.)?    - www. 0 or 1 time
example.com - example.com

i标志表示整个表达式不区分大小写,因此HTTP://WWW.EXAMPLE.COM也会匹配。

答案 2 :(得分:1)

/^http:\/\/(www\.)?example.com/i

1) ^ - carret (matches start of line / string)
2) http: - matches the actual 'http:' string
3) \/\/ - matches // (needs escaping with \)
4) (www\.)? - can contain or not the string 'www.' (? = 0 or 1 times)
5) example.com - matches the actual 'example.com' string
6) trailing i - case insensitive

答案 3 :(得分:1)

正则表达式:

/^http:\/\/(www\.)?example.com/i

正如javascript中所解释的那样,regexp在forme(http://www.w3schools.com/js/js_obj_regexp.asp)中:

/pattern/modifiers

所以模式

^http:\/\/(www\.)?example.com

^

开头

http:\/\/'http://'使用斜杠转义

(www\.)? 0或1次'www。'

example.com'示例',任何字符表示新行,'com'

如果您只想要'example.com',请使用example\.com

修饰符:

i不区分大小写