Regular expression to match up to the last 3 characters before the comma

It might have been asked somewhere, but of course I couldn't find the answer I want:

I'm having a hard time matching certain characters in a string:

"88551554,86546546,51516565"

      

The numbers I want to match are the following Xs:

"XXXXX554,XXXXX546,XXXXX565"

      

Right now I can only find out the last 3 digits before each comma:

\d{3}(?=,)

      

And since the length of numbers is dynamic, it seems impossible to specify the number of digits before 3 digits.

Anyone can help?

Thanks in advance!

+3


source to share


2 answers


You can use this lookahead regex:

(\d+)(?=\d{3}(?:,|$))

      

Demo version of RegEx

This will match and group 1 or more digits, followed by 3 digits and a comma or end of input. Check INFORMATION FOR MATCH in the demo link for captured groups.




Update: To replace all these matched numbers with X

, use:

str = str.replaceAll("\\d(?=\\d*\\d{3}(?:,|$))", "X");

      

RegEx Demo2

+3


source


To match it use:

\d+(?=\d{3})

      



This is a regex:

\d+

... Match a digit (0-9) between one and unlimited time.
 (?=\d{3})

... Match the digit (0-9) exactly three times within the positive view.

+1


source







All Articles