简体   繁体   English

为什么此正则表达式不能在javascript中工作(在perl中有效)

[英]Why isn't this regex working in javascript (works in perl)

I'm trying to match the following string, 我正在尝试匹配以下字符串,

Apache/2.2.6 (Unix) mod_ssl/2.2.6 OpenSSL/0.9.7a DAV/2 PHP/5.2.13

with the following regex, 使用以下正则表达式,

(?:Apache.(\\w+))?.*(?:OpenSSL.([\\w.]+))?.*(?:PHP.([\\w.]+))?

Since the XXX/version pairs may not exist, so I added a ? 由于XXX/version对可能不存在,因此我添加了一个? after each non-capture matching groups 在每个非捕获匹配组之后

But only the first version string is matched, 但是只有第一个版本字符串匹配,

var re = /(?:Apache.([\w.]+))?.*(?:OpenSSL.([\w.]+))?.*(?:PHP.([\w.]+))?/;
var captures = re.exec('Apache/2.2.6 (Unix) mod_ssl/2.2.6 OpenSSL/0.9.7a DAV/2 PHP/5.2.13');
console.log (captures);

// captures[1] = '2.2.6'
// captures[2] = undefined
// captures[3] = undefined

Any ideas? 有任何想法吗? Removing the '?' 删除“?” works and I don't know why (works with perl) 有效,我不知道为什么(与perl兼容)

EDIT 编辑

A valid regex that "works" could be (without the '?'), 有效的正则表达式可以“起作用”(不带“?”),

(?:Apache.(\\w+)).*(?:OpenSSL.([\\w.]+)).*(?:PHP.([\\w.]+))

.* is greedy so I'm not surprised it's not capturing beyond the first group. 。*很贪婪,所以我不惊讶它没有超出第一组。 What surprises me is that it worked at all anywhere. 令我惊讶的是它在任何地方都可以使用。 Make those catch-alls lazy and un-group the non-capturing and capturing groups and it seems to work: 使那些包罗万象的人变得懒散,取消对未捕获和捕获的组的分组,这似乎可行:

(?:Apache.)(\w+)?.*?(?:OpenSSL.)([\w.]+)?.*?(?:PHP.)([\w.]+)?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM