I have a simple problem and yet to find the optimal solution.
Imagine I have a url with a query param named 'id' like any of the following formats
I'm taking the above string (could be any one above) as a String parameter and want to figure out the simplest way to remove the query parameter id (name and value), so that even after removing, it will be a valid url.
Below are my expected outputs (in order).
Can anyone have a good idea? (only with String operations, without any util classes)
You can use replaceAll
which is using regex like so :
String[] urls = new String[]{
"xxxxxxxxxxxxx?id=123", "xxxxxxxxxxxxx?id=123&xxxxxxxx",
"xxxxxxxxxxxxx?xxxxxx&id=123", "xxxxxxxxxxxxx?xxxxxx&id=123&xxxxx"
};
for (String url : urls) {
System.out.println(
url.replaceAll("([\\?&]id=\\d+$)|(id=\\d+&)", "")
);
}
Output
xxxxxxxxxxxxx
xxxxxxxxxxxxx?xxxxxxxx
xxxxxxxxxxxxx?xxxxxx
xxxxxxxxxxxxx?xxxxxx&xxxxx
Details
this regex ([\?&]id=\d+$)|(id=\d+&)
mean to match :
([\?&]id=\d+$)
first group
[\?&]
match literal ?
or &
characterid
followed by literal id
word\d+
followed by one or mode digit$
end of line|
or (id=\d+&)
match group two
id
match literal id
word\d+
followed by one or mode digit&
match literal &
characterIf you the input after id=
can be other than a digit you can use \w
instead which match \w word character which can match any character in [A-Za-z0-9_]