user3206108
user3206108

Reputation: 33

Java replace any numbers in a URL between or after slashes

I've been banging my head against a wall for the last hour trying to come up with an eloquent way using Java (the application is in Java so I have to use it) to handle a particular problem. I am trying to replace any number (even if it has leading zeros) in a RESTful URL with hashtags so that we can track how many times a particular call was made, regardless of ID. Here are some examples of what I'm looking to do:

http://host.com/api/person/1234 needs to be http://host.com/api/person/#####

http://host.com/api/person/1234/jobs needs to be http://host.com/api/person/#####/jobs

http://host.com/api/person/1234/jobs/321 needs to be http://host.com/api/person/#####/jobs/#####

http://host.com/api/person/abc1234/jobs needs to stay http://host.com/api/person/abc1234/jobs

The hashtags that will be inserted will always be 5 hashtags to keep things uniform. I have this working using two steps, I was trying to figure out a way using regex and replaceAll to do it in one, although if anyone else knows of a better way to do it in one step I'm open to that as well.

Upvotes: 1

Views: 556

Answers (1)

developer033
developer033

Reputation: 24894

You can use replaceAll() method with this simple regex:

(?<=/)\\d+

Which means "match all numbers after slash (/)".

Example:

List<String> urls = Arrays.asList("http://host.com/api/person/1234", "http://host.com/api/person/1234/jobs", "http://host.com/api/person/1234/jobs/321", "http://host.com/api/person/abc1234/jobs", "http://host.com/api/person/1234abc/jobs");
for (int i = 0; i < urls.size(); i++) {
   urls.set(i, urls.get(i).replaceAll("(?<=/)\\d+(?=/|$)", "#####"));
}
System.out.println(urls.toString());

// Result:
// [http://host.com/api/person/#####, http://host.com/api/person/#####/jobs, http://host.com/api/person/#####/jobs/#####, http://host.com/api/person/abc1234/jobs, host.com/api/person/1234abc/jobs]

Ideone

Upvotes: 2

Related Questions