How to use a regular expression to print repeating characters only once and non repeating characters in the same order as they appear in a String?

I'm writing a function to print decimal representation of a rational number( in the form of numerator and denominator) and trying to print the repeating part of digits inside a parenthesis and decimal part remains the same.

for EX: 1) 2/3=0.(3)
        2) 2/4=0.5(0)
        3)22/7=3.(142857)

For this I tried using a regular expression to capture the repeating characters of decimal part but my regular expression captures the repeating characters once and non repeating characters.

Here is my code...Can someone help me on this!!!

div = ((double) num)/deno;
String str = String.valueOf(div);
String arr[] = str.split("\\.");
String wp = arr[0];
String dp = arr[1];
String repeated = dp.replaceAll("(.+?)\\1+", "$1");
System.out.println("repeated is " + repeated);
System.out.println(wp + "." + "(" + repeated + ")");`

output I'm getting is:-

Input given 22/7
Integer part: 3
Decimal part: 142857142857143
repeating characters captured by regular expression- 142857143
final output-3.(142857143)

1 answer

  • answered 2021-04-08 05:23 onkar ruikar

    When you are replacing the repeating part, the last 143 is not getting replaced with `` empty string. So it remains in the output.
    You can use Pattern class, with regex (\d+)+\1, like this:

    public class Test
    {
        public static void main(String[] args) throws Exception
        {
            double[] nums = {2.0/3, 2.0/4, 22.0/7};
            for(double d : nums)
                print(d);
        }
        
        static void print(double div) {
            String str = String.valueOf(div);
            String arr[] = str.split("\\.");
            String wp = arr[0];
            String dp = arr[1];
            String repeated = dp;
            Pattern ptrn = Pattern.compile("(\\d+)+\\1");
            Matcher m = ptrn.matcher(dp);
            if(m.find()) {
                repeated = m.group(1);
                System.out.println(str + " -> "+ wp + "." + "(" + repeated + ")");
            } else {
                System.out.println(str + " -> "+ wp + "." + dp +"(0)");
            }
        }
    }
    

    Output:

    0.6666666666666666 -> 0.(6)
    0.5 -> 0.5(0)
    3.142857142857143 -> 3.(142857)