+ Start a Discussion

Syntax error with Apex Number formatting - Regex


I am trying to use REGEX in Apex for achieving to format a number with commas

Number stored as -->11111
Should look like --> 11,111

There is no scenario to use decimal, so need positive ineteger REGEX , I tried various combinations and always get the error while saving
string strHeader = String.valueOf(tiers.StartValue__c.intvalue());
string StrHeaderValue;

// First Option
//StrHeaderValue =strHeader.split('/'(?=(?:\d{3})+(?:'\.'|$))/g).join(',');

//Second Option
//StrHeaderValue =strHeader.split(('//')(?=(?:\d{3})+(?:('//.')|$))/g).join(',');

//Third Option
StrHeaderValue=strHeader.replace('/(\d)(?=(\d\d\d)+(?!\d))/g', '$1,');

//Fourth Option
//StrHeaderValue = strHeader.replace('//'('\\'d{3})(?=\d)'//'g, '$1,');

so.put(field, String.valueOf(tiers.StartValue__c.intvalue() + '+'));
so.put(field, StrHeaderValue );

Currently trying the option3 , It shows an error on saving "Invalid string Literal" or the '/' character is not allowed

How should be use / character?
Alain CabonAlain Cabon

With replaceAll  ( instead of replace )
integer[] tiers = new integer[]{11,111,22111,222111,3222111,333222111};
string val1;
string val2;
for (integer tier:tiers) {
	 val1 = String.valueOf(tier);
	 val2 =val1.replaceAll('(\\d{3})??(\\d{3})??(\\d{3})$','$1,$2,$3').replace(',,',',').replaceAll('^,+','');

Limit here: 999,999,999 (three groups).

With split, there is probably another solution.