正则表达式匹配字符串,直到whitespace Javascript

时间:2014-08-11 17:58:50

标签: javascript regex string whitespace

我希望能够匹配以下示例:

www.example.com
http://example.com
https://example.com

我有以下正则表达式与www.不匹配但匹配http:// https://。我需要匹配上面示例中的任何前缀,直到下一个空格,从而匹配整个URL。

var regx = ((\s))(http?:\/\/)|(https?:\/\/)|(www\.)(?=\s{1});

假设我有一个如下所示的字符串:

I have found a lot of help off www.stackoverflow.com and the people on there!

我想在该字符串上运行匹配并获取

www.stackoverflow.com

谢谢!

3 个答案:

答案 0 :(得分:7)

你可以尝试

(?:www|https?)[^\s]+

这是online demo

示例代码:

var str="I have found a lot of help off www.stackoverflow.com and the people on there!";
var found=str.match(/(?:www|https?)[^\s]+/gi);
alert(found);

模式说明:

  (?:                      group, but do not capture:
    www                      'www'
   |                        OR
    http                     'http'
    s?                       's' (optional)
  )                        end of grouping
  [^\s]+                   any character except: whitespace 
                            (\n, \r, \t, \f, and " ") (1 or more times)

答案 1 :(得分:0)

你的正则表达式中有错误。

使用此:

((\s))(http?:\/\/)|(https?:\/\/)|(www\.)(?!\s{1})
                                          ^--- Change to negative lookaround
是的,我认为你可以使用:

(?:(http?:\/\/)|(https?:\/\/)|(www\.))(?!\s{1})

MATCH 1
3.  [0-4]   `www.`
MATCH 2
1.  [16-23] `http://`
MATCH 3
2.  [35-43] `https://`

答案 2 :(得分:0)

不太确定你要做什么,但这应该匹配任何一组非空格字符,而不是紧跟在“www”之前。不区分大小写。

/(https?:\/\/)?(?<!(www\.))[^\s]*/i

... [编辑]但你 希望匹配www。

/(https?:\/\/)?([^\s\.]{2,}\.?)+/i