Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

regex

I'm trying use regular expression to convert special characters in an 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 ?_%. to "-" excluding "/".

The regular expression in my code converts everything resulting the output as

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.

like image 435
Shamik Avatar asked Jul 18 '26 08:07

Shamik


2 Answers

You could just add your / into the regex:

"[^a-zA-Z0-9/]"
like image 63
Paul Avatar answered Jul 20 '26 23:07

Paul


formatUrl = formatUrl.replaceAll("[^a-zA-Z0-9/]" , "-");
like image 32
Jonathan M Avatar answered Jul 20 '26 22:07

Jonathan M



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!