Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/326.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 正则表达式匹配url目录路径,但不匹配文件名_Java_Regex - Fatal编程技术网

Java 正则表达式匹配url目录路径,但不匹配文件名

Java 正则表达式匹配url目录路径,但不匹配文件名,java,regex,Java,Regex,我想要一个匹配的正则表达式 https://example.com/studio/或https://example.com/studio不匹配https://example.com/studio/path-to-file-blah-blah或https://example.com/studio/path-to-file-blah-blah.html 我尝试了https?:\/\/(?:w{3}[.])?示例[.]com\/studio\S*,但它与上面的两个组都匹配 我还尝试了https?:\/

我想要一个匹配的正则表达式

https://example.com/studio/
https://example.com/studio
不匹配
https://example.com/studio/path-to-file-blah-blah
https://example.com/studio/path-to-file-blah-blah.html

我尝试了
https?:\/\/(?:w{3}[.])?示例[.]com\/studio\S*
,但它与上面的两个组都匹配


我还尝试了
https?:\/\/(?:w{3}[。])?示例[.]com\/studio\/?
,它只能匹配第一组。但问题是只匹配第二组。请问我该怎么做?

我假设您需要从非结构化文本解析URL。假设有空格字符、新行字符或字符串的结尾,下面的代码应该适合您。如果URL后面直接有句点或其他字符,则此操作将失败,但很容易修改以支持其他终止字符

https?:\/\/(?:w{3}[.])?example[.]com\/studio\/?(?:\s|$)
(?:\s |$)
只说匹配空格字符(包括换行字符的行尾)或匹配字符串的结尾

编辑

我想你是说第二组是:

https://example.com/studio/path-to-file-blah-blah
https://example.com/studio/path-to-file-blah-blah.html
要匹配这些,您需要以下正则表达式:

https?:\/\/(?:w{3}[.])?example[.]com\/studio\/\S+
我所做的唯一更改是最后一个字符是
\S*
,但它应该是
\S+

*
表示0或更多

+
表示一个或多个


希望这涉及到你在寻找什么。如果我仍然不在,如果你给组加上标签,它会帮助我理解,这样我就可以写出正确的正则表达式。

进一步扩展Nathan的答案,你可以更改正则表达式的结尾,以不捕获尾随空格或新行。这将匹配前两种情况:

https?:\/\/(?:w{3}[.])?example[.]com\/studio\/?(?=\s|$)
要仅匹配第二种情况,请使用以下命令:

https?:\/\/(?:w{3}[.])?example[.]com\/studio(?=[^\/])

谢谢,但是你的正则表达式与第一组匹配,但正如我在问题中所说,我已经找到了解决方法。我只需要匹配第二组。对不起,我一定是误解了你的意思。我以为你只想匹配
https://example.com/studio/
https://example.com/studio
。您还想匹配哪些其他案例?您提供的正则表达式将匹配
https://example.com/studio/path-to-file-blah-blah
而我的不会。在我的问题中,我写了两个正则表达式:
https?:\/\/(?:w{3}[。])?示例[.]com\/studio\S*
https?:\/\/(?:w{3}[。])?示例[.]com\/studio\/?
。第一个匹配两个组,而第二个仅匹配第一个组。所以我想要一个只匹配第二组的正则表达式。