简体   繁体   English

检查正则表达式是否与可选组匹配

[英]Check if a regex matched an optional group

I'm trying to match an HTTP request line and to fetch the requested item. 我正在尝试匹配HTTP请求行并获取请求的项目。 I have the following regular expression: 我有以下正则表达式:

Pattern regex = Pattern.compile("GET /(\\w+\\.\\w+)? HTTP/1.1");

If you check it, you will notice an optional group (\\\\w+\\\\.\\\\w+)? 如果选中它,您会注意到一个可选组(\\\\w+\\\\.\\\\w+)? . When I send a file, like for example GET /index.html HTTP/1.1 it works correctly and matcher.groupCount() returns 1 . 当我发送文件时,例如GET /index.html HTTP/1.1它可以正常工作,并且matcher.groupCount()返回1 The problem is when I send something like GET / HTTP/1.1 . 问题是当我发送类似GET / HTTP/1.1 I don't know how to check if the group has been matched, since matcher.groupCount() returns 1 as well. 我不知道如何检查组是否已匹配,因为matcher.groupCount()返回1 I suspect that the groupCount() function returns the number of groups in the regex regardless of their existence in the parsed String. 我怀疑groupCount()函数返回正则表达式中的组数,无论它们存在于已解析的String中。

Thanks 谢谢

You don't need to use optional group here actually. 您实际上不需要在这里使用可选组。 This regex will work better for you: 此正则表达式将更适合您:

Pattern regex = Pattern.compile("GET (/\\S+) HTTP/1\.1");

ie match & capture everything from first / until you hit a space as the REQUEST URI . 即匹配并捕获所有内容,从第一个/直到您打一个空格作为REQUEST URI

Remember a web request can contain query parameters also with ? 还记得一个Web请求可以包含查询参数? , & etc and \\\\w+\\\\.\\\\w+ is not a good regex to match them all. &等和\\\\w+\\\\.\\\\w+不是一个很好的正则表达式来匹配它们。

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

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