Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java place a "-" between odd numbers in a string using regex

Tags:

java

string

regex

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

like image 916
Help123 Avatar asked Jul 24 '15 20:07

Help123


1 Answers

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

  • odd number before use look behind (?<=[13579]),
  • odd number after it use look-ahead (?=[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");
like image 93
Pshemo Avatar answered Sep 20 '22 22:09

Pshemo