Java pattern for finding duplicate groups

I would like to get a repeating part in a repeating beat. For example, if the fraction is 0.6666667, I would like to get 0.67 and the repeated part (6), or for 0.36363636 0.36 and (36) as the concurrent group. I've tried using capture groups in Java, but I'm not sure if I'm doing it right. Here's what I have right now:

String patt = "(.+?)\\1+";

      

Unfortunately, this corresponds to 0.003003003 as "0". Is there a way to get "003" here?

+3


source to share


2 answers


I don't see the underlying problem you are trying to solve. It seems what you want to do is not textual but rounding.

Try the following:

BigDecimal r = new BigDecimal("0.66666667").setScale(2, RoundingMode.HALF_UP);
System.out.println(r);

      

It will show:



0.67

      

Likewise, for 0.363636...

he will give you 0.36

etc.

If you really want to use a regex and all your inputs are 0

up to the decimal point, you can try

0\.(.+?)\\1+

      

+1


source


"(.+)\\1+"

must find 003

by taking the longest sequence with index 2.



0


source







All Articles