function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
SAHG-SFDCSAHG-SFDC 

Syntax error with Apex Number formatting - Regex

Hi,

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
Hi,

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('^,+','');
     system.debug('test:'+val1+'='+val2);
}

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

With split, there is probably another solution.

Regards