I am trying to place a -
between all odd numbers in a string. So if a string is passed in as Hel776o
it should output Hel7-76o
. Dashes should only be placed between two consecutive odd numbers.
I am trying to do this in one line via String.replaceAll()
I have the following line:
return str.replaceAll(".*([13579])([13579]).*","$1-$2");
If any odd number, followed by an odd number place a -
between them. But it's destructively replacing everything except for the last match.
Eg if I pass in "999477"
it will output 7-7
instead of9-9-947-7
. Are more groupings needed so I don't replace everything except the matches?
I already did this with a traditional loop through each char in string but wanted to do it in a one-liner with regex replace.
Edit: I should say I meant return str.replaceAll(".*([13579])([13579]).*","$0-$1");
and not $1
and $2
Remove .*
from your regex to prevent consuming all characters in one match.
Also if you want to reuse some part of previously match you can't consume it. For instance if your string will be 135
and you will match 13
you will not be able to reuse that matched 3
again in next match with 5
.
To solve this problem use look-around mechanisms which are zero-length which means they will not consume part they match.
So to describe place which has
(?<=[13579])
, (?=[13579])
.So your code can look like
return str.replaceAll("(?<=[13579])(?=[13579])","-");
You can also let regex consume only one of two odd numbers to let other one be reused:
return str.replaceAll("[13579](?=[13579])","$0-");
return str.replaceAll("(?<=[13579])[13579]","-$0");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With