Kenneth
Kenneth

Reputation: 343

replace char in specific pattern or after specific character

The task at hand is to replace "-" with "/" in a birthday format e.g. 03-12-89 -> 03/12/89. However, the "-" must be able to appear elsewhere in the string e.g. "My-birthday-is-on-the: 03/12/89".

I have tried creating substrings, replace the "-" in the birthday part and then combine the strings again. However, that solution is inflexible and fails the testcases.

I'm thinking I must be able to do this with a regular expression, although I seem unable to construct it. So now I'm back to: String newStr = input.replace("-", "/"); Which remove all instances of "-" which I don't want.

Can anyone help?

Upvotes: 0

Views: 49

Answers (2)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521269

The easiest way which comes to mind is just match \d{2}-\d{2}-\d{2}, with capture groups. Then, use those captured numbers to rebuild the birthdate the way you want it. Something like this:

String input = "My-birthday-is-on-the: 03/12/89";
input = input.replaceAll("\\b(\\d{2})-(\\d{2})-(\\d{2})\\b", "$1/$2/$3");

Demo

The advantage of specifying the full pattern is that it avoids the chance of matching anything other than a 6 digit dash-separated birthday.

Edit:

Based on your comment below, it sounds like maybe you want to do this replacement on a two dash separated number, with any number of digits. In this case, we can slightly modify the above code to the following:

String input = "Your policy number is: 123-45-6789.";
input = input.replaceAll("\\b(\\d+)-(\\d+)-(\\d+)\\b", "$1/$2/$3");

Upvotes: 2

Allan
Allan

Reputation: 12438

You can use the following regex:

(?<=\d{2})-

with replacement \/ (no need to escape it in Java)

INPUT:

My-birthday-is-on-the: 03-12-89

OUTPUT:

My-birthday-is-on-the: 03/12/89

demo

Code:

String input = "My-birthday-is-on-the: 03-12-89";
System.out.println(input.replaceAll("(?<=\\d{2})-", "/"));

OUTPUT:

My-birthday-is-on-the: 03/12/89

Upvotes: 3

Related Questions