组合捕获组,不同的匹配数

时间:2016-07-01 10:00:46

标签: javascript regex

我正在努力让一些正则表达式工作,但我无法让捕获组分享(?)匹配。我希望如此,如果正则表达式匹配" id",它使用正则表达式匹配所有数字(17长),如果匹配" profile",它匹配字母数字。现在,当我尝试以下时,它可以工作,但配置文件的匹配是第3和第4,而不是第1和第2。希望这是有道理的。

这是一个正则表达式测试:https://regex101.com/r/wS2pL0/2

http://community.com/id/something123
http://community.com/profile/12345678901234567

(?:https?:\/\/)(?:www\.)?community\.com\/(?:(id)\/(\w{3,32})|(profile)\/(\d{17}))

1 个答案:

答案 0 :(得分:0)

        var regex   = /(?:https?:\/\/)(?:www\.)?community\.com\/(id\/\w{3,32}|profile\/\d{17})/; 
        var string  = document.getElementById('url').value;
        var match   = string.match(regex);

        if (match) {
            var mat = match[1].split('/');
            if (mat[0] == 'profile' && mat[1].length === 17) {
                console.log("true" + mat[1]);
            } else {
                console.log("false");
            }
        } else {
            console.log('nothing');
        }
相关问题