正则表达式在匹配后停止,并且在使用“轮换”符号时不再匹配

时间:2015-09-10 05:33:43

标签: javascript regex

我试图从昨天开始解决这个问题,并且相信我错过了一些非常简单的事情。

我写了一个正则表达式来匹配三种IP地址格式中的任何一种:

Pattern to match : X.X.X.X OR X.X.X.X/X.X.X.X OR X.X.X.X-X.X.X.X

正则表达式:

/^(([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\/([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5]))|(([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\-([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5]))|(([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5]))$/

问题:

正则表达式与上述3种格式相匹配,但问题在于交替 符号 - 行为就像找到匹配后正则表达式停止一样。

Example: 1.1.1.1/1.1.1.1 - Once this match is found it does not check after that.

i.e: 1.1.1.1/1.1.1.1 - Valid 

 But 1.1.1.1/1.1.1.1(...anything after this is also recognized as valid which should not be the case...)

问题:

如何使其仅匹配3种替代品中的一种。我也尝试了word boundaries (\b),但我不确定这是否是需要的。

任何帮助表示感谢。

3 个答案:

答案 0 :(得分:1)

问题在于交替具有所有正则表达式构造的最低优先级。你的正则表达式匹配:

^X.X.X.X/X.X.X.X    // anchored at start only

X.X.X.X-X.X.X.X     // not anchored 

X.X.X.X$            // anchored at end only

您可以通过在除锚点之外的所有内容中添加另一组括号来修复它:

^(your regex)$

答案 1 :(得分:1)

试试这个正则表达式:

(^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$)|(^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)[\/-](?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$)

您可以使用以下链接进行测试以进行验证。

https://regex101.com/r/fC6uS3/1

答案 2 :(得分:0)

您可以将正则表达式缩短为:

int

如果您使用javascript运行它,则会使用^(((([0-2][0-5][0-6])|(\d{1,2}))\.){3}((([0-2][0-5][0-6])|(\d{1,2}))))([/-](((([0-2][0-5][0-6])|(\d{1,2}))\.){3}(([0-2][0-5][0-6])|(\d{1,2}))))*$

/.../
var pattern = new RegExp(/^(((([0-2][0-5][0-6])|(\d{1,2}))\.){3}((([0-2][0-5][0-6])|(\d{1,2}))))([/-](((([0-2][0-5][0-6])|(\d{1,2}))\.){3}(([0-2][0-5][0-6])|(\d{1,2}))))*$/);
var testCases = {};

//should work
testCases['testCaseA'] = '1.2.3.4';
testCases['testCaseB'] = '1.2.3.4/1.256.3.4';
testCases['testCaseC'] = '1.2.3.4-1.2.3.4';

//should not work
testCases['testCaseD'] = '1.257.3.4';
testCases['testCaseE'] = '1.2.3.4/1.2.3.356';
testCases['testCaseF'] = '1.2.3.4-1.2.3.4I';
var results = '<table><tr><th>Cases</th><th>Inputs</th><th>Outputs</th></tr>';
$.each(testCases, function(k, v) {
results += '<tr><td>' + k + '&emsp;&emsp;</td><td>' + v + '&emsp;&emsp;</td><td>' + pattern.test(v) + '</td>';
});
document.write(results + '</table>');