Application Development and Automation Discussions
Join the discussions or start your own on all things application development, including tools and APIs, programming models, and keeping your skills sharp.
cancel
Showing results for 
Search instead for 
Did you mean: 
Read only

Replace Non-Numeric Characters with a Numeric Character in a String

Former Member
0 Likes
6,179

Hi Guys,

I need to replace all the non-numeric characters (including embedded blanks & hyphen) in a string to a numeric character '1'.

The trailing blanks should not be replaced.

e.g. "P22233344455566" should be changed to "122233344455566"

& "49-1234567 " should be changed to "4911234567 "

Please help.

4 REPLIES 4
Read only

Former Member
2,365

Use [replace|http://help.sap.com/abapdocu_70/en/ABAPREPLACE_IN_PATTERN.htm] with a regular expression to translate any non-numeric character (i.e. any character not between 0 and 9) to 1:


  REPLACE ALL OCCURENCES OF REGEX '[^0-9]' IN value WITH '1'.

Cheers, harald

p.s.: In older releases [translate|http://help.sap.com/abapdocu_70/en/ABAPTRANSLATE.htm] would also do the trick, but is more lengthy, because one would need to specify each individual character that should be replaced, e.g.:


  TRANSLATE value TO UPPER CASE.
  TRANSLATE value USING
      ' 1_1-1a1b1c1d1e1f1g1h1i1j1k1l1m1n1o1p1q1r1s1t1u1v1w1x1y1z1'.

Read only

0 Likes
2,365

If I use the code suggested by you the trailing blanks are also getting replaced by '1'.

e.g. if the string is of 15 characters and the value is "a13-4 567g23 ", it is getting changed as "113141567123111".

but it should be changed as "113141567123".

The trailing blanks should be left as it is and should not be replaced by '1'.

Please help.

Read only

0 Likes
2,365

Do a condense before replacing.

Read only

0 Likes
2,365

For keeping trailing blanks use this [replace|http://help.sap.com/abapdocu_70/en/ABAPREPLACE_IN_PATTERN.htm] statement instead:


REPLACE ALL OCCURENCES OF REGEX '[^0-9](?! *$)' IN value WITH '1'.

You cannot use [condense|http://help.sap.com/abapdocu_70/en/ABAPCONDENSE.htm], because it processes all blanks in a string, not just the trailing blanks (and per your statement it sounds like you want to keep them, which is accomplished via the statement I've given above).

Cheers, harald