Home > front end >  ABAP: REPLACE REGEX end of string
ABAP: REPLACE REGEX end of string

Time:10-06

I want to remove " %" at the end of some text. I'd like to do it with a regular expression, because ABAP does not easily handle text at the end of a string.

REPLACE REGEX ' %$' IN lv_vtext WITH ''.

But it does not replace anything. When I leave out "$" the text will be removed as expected, but I fear it might find more occurrences than wanted.

I experimented with \z or \Z instead of $, but to no avail.

CodePudding user response:

You can use

REPLACE REGEX '\s%\s*$' IN lv_vtext WITH ''

The benefit of using \s is that it matches any Unicode whitespace chars. The \s*$ matches any trailing (white)spaces that you might have missed.

The whole pattern matches

  • \s - any whitespace
  • % - a % char
  • \s* - zero or more whitespaces
  • $ - at the end of string.

CodePudding user response:

This answer is about an alternative way without REGEX. POSIX regular expressions are quite slow, moreover some people are reluctant to use it, so if you're not completely closed to do it in normal ABAP:

lv_vtext = COND #( WHEN contains( val = lv_vtext end = ` %` ) 
           THEN substring( val = lv_vtext len = strlen( lv_vtext ) - 2 )
           ELSE lv_vtext ).

Code with context:

DATA(lv_vtext) = `test %`.
lv_vtext = COND #( WHEN contains( val = lv_vtext end = ` %` ) 
           THEN substring( val = lv_vtext len = strlen( lv_vtext ) - 2 )
           ELSE lv_vtext ).
ASSERT lv_vtext = `test`.
  • Related