简体   繁体   English

如何使用 Java 正则表达式替换 URL 中的所有特殊字符?

[英]How can I replace all special characters in a URL, using a Java regular expression?

I'm trying use regular expression to convert special characters in an url.我正在尝试使用正则表达式转换 url 中的特殊字符。 Here's my sample code:这是我的示例代码:

String formatUrl = "index.php?title=Test/enu/test/Tips_%26_Tricks/Tips_and_Tricks";
formatUrl = formatUrl.replaceAll("[^a-zA-Z0-9]" , "-");

What I'm trying to do is to convert the special characters in the url such as?_%.我要做的是转换 url 中的特殊字符,例如?_%。 to "-" excluding "/".到“-”,不包括“/”。

The regular expression in my code converts everything resulting the output as我的代码中的正则表达式将导致 output 的所有内容转换为

index-php-title-Test-enu-test-Tips--26-Tricks-Tips-and-Tricks

But I want it to be但我希望它是

index-php-title-Test/enu/test/Tips--26-Tricks/Tips-and-Tricks

Any pointers will be appreciated.任何指针将不胜感激。

You could just add your / into the regex:您可以将/添加到正则表达式中:

"[^a-zA-Z0-9/]"
formatUrl = formatUrl.replaceAll("[^a-zA-Z0-9/]" , "-");

I'm wondering what you're trying to achieve.我想知道你想达到什么目的。 Why not just decode the URL?为什么不直接解码 URL?

final String url = "index.php?title=Test/enu/test/Tips_%26_Tricks/Tips_and_Tricks";
final String decoded = java.net.URLDecoder.decode(url, "UTF-8");
System.out.println(decoded); // Prints index.php?title=Test/enu/test/Tips_&_Tricks/Tips_and_Tricks

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

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