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

I am trying to fit - between all odd numbers in a string. Therefore, if a string is passed as Hel776o , it should output Hel7-76o . Dashes should only be placed between two consecutive odd numbers.

I am trying to do this on one line through String.replaceAll ()

I have the following line:

 return str.replaceAll(".*([13579])([13579]).*","$1-$2"); 

If there is any odd number followed by an odd number, put a - between them. But it destructively replaces everything except the last match.

For example, if I go through "999477" , it will print 7-7 instead of 9-9-947-7 . More groupings required, so I won’t replace everything except matches?

I already did this with a traditional loop through each char line, but wanted to do it in a single line file with regular expression replacement.

Edit: I have to say what I meant by return str.replaceAll(".*([13579])([13579]).*","$0-$1"); , not $1 and $2

+6
source share
1 answer

Remove .* From your regular expression to prevent all characters from being used in a single match.

Also, if you want to reuse part of a previous match, you cannot use it. For example, if your string is 135 and you match 13 , you cannot reuse this match 3 in the next match with 5 .
To solve this problem, use look-around mechanisms that are zero length , which means that they will not consume the part that they match.

So, to describe the place that has

  • Odd number before use peek behind (?<=[13579]) ,
  • An odd number after using the search function (?=[13579]) .

So your code might look like

 return str.replaceAll("(?<=[13579])(?=[13579])","-"); 

You can also allow the regex to consume only one of two odd numbers to allow reuse of the other:

 return str.replaceAll("[13579](?=[13579])","$0-"); return str.replaceAll("(?<=[13579])[13579]","-$0"); 
+9
source

All Articles