简体   繁体   English

如何使用Regex从URL提取路径?

[英]How to extract path from URL using Regex?

I want to extract path from url. 我想从网址中提取路径。

www.abc.com/contact/abc => /contact 
www.abc.com/contact.abc/asdsad => /contact.abc
www.abc.com/contact-abc.html/asdsad => /contact-abc.html
www.abc.com/contact-2 => /contact-2
www.abc.com/contact-us => /contact-us
abc&/contact.abc&^ = /contact.abc

What single regex could do this? 哪一个正则表达式可以做到这一点?

\/([0-9a-zA-Z+.-]+)[\/&| ]

This one could be a solution, though it is strictly related to the urls you gave in your question as examples. 这可能是一个解决方案,尽管它与您在问题中提供的网址严格相关,例如。

I'll leave you the link to regexr so that you can understand what is there actually behind. 我将为您保留regexr的链接,以便您可以了解实际的内容。

Regexr resource 正则资源

If you are using Java, use java.net.URL class to parse URL and getPath method to get its path as explained here, no need for regex: 如果您使用的是Java,请使用java.net.URL类解析URL,并使用getPath方法获取其路径,如此处所述,无需使用正则表达式:

https://docs.oracle.com/javase/tutorial/networking/urls/urlInfo.html . https://docs.oracle.com/javase/tutorial/networking/urls/urlInfo.html

For regex, refer to this in question: 对于正则表达式,请参考相关问题:

Getting parts of a URL (Regex) 获取URL的一部分(正则表达式)

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

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