ABAP Keyword Documentation → ABAP - Reference → Processing Internal Data → Character String and Byte String Processing → Expressions and Functions for String Processing → String Functions → Processing Functions for Character-Like Arguments
replace - Replace Function
Other versions: 7.31 | 7.40 | 7.54
Syntax Forms
-
... replace( val = text [off = off] [len = len]
with = new ) ... -
... replace( val = text {sub = substring}|{regex = regex}
with = new [case = case] [occ = occ] ) ...
Effect
This function replaces a subfield of text
with the character string specified in new and returns the changed text.
The substring is determined as follows:
- The variant with the arguments
offandlenreplaces the subfield defined by the offsetoffand the lengthlen. At least one of these additions must be defined.
- The variant with the arguments
suborregexscans thetextfor the occurrence specified inoccfor a match with the substring specified insubstringor with a regular expression specified inregexand replaces the found location. Ifocccontains the value 0, all found locations are replaced. Ifsubstringis empty, an exception from the class CX_SY_STRG_PAR_VAL is raised. The search is case-sensitive by default, but can be overridden using the parameter case. If no substring is found, the unchanged content oftextis returned.
new is a character-like expression position. If they have a fixed length, trailing blanks are ignored.
The return code has the type string accordingly.
Notes
- Borderline cases for the variants with the arguments
offandlen:
- If only
offis specified or if the value 0 is specified forlen, thenreplacefunctions likeinsert.
- If only
lenis specified or ifoffhas the value 0, then the first segment of the lengthlenis replaced.
- If the value of
offis equal to the length oftext, then the value oflenmust be equal to 0 orlenis not specified. The character stringnewis then attached to the end oftext.
- If a regular expression is used with
regexthen special replacement models that allow references to particular found locations can be specified innew.
Example
The result of the following replacement is "<title>Th<b>i</b>s <b>i</b>s the <i>T<b>i</b>tle</i> </title>". In an HTML line, a particular letter is placed in format tags if it is not itself in a tag.
DATA: html TYPE string,
repl TYPE string.
html = `<title>This is the <i>Title</i></title>`.
repl = `i`.
html = replace( val = html
regex = repl && `(?![^<>]*>)`
with = `<b>$0</b>`
occ = 0 ).
Exceptions
Catchable Exceptions
CX_SY_RANGE_OUT_OF_BOUNDS
-
Cause: Illegal offset or length specification in the
offandlen.
Runtime Error:STRING_OFFSET_TOO_LARGE
CX_SY_REGEX_TOO_COMPLEX
-
Cause: More information: Exceptions in Regular Expressions.
Runtime Error:REGEX_TOO_COMPLEX
CX_SY_STRG_PAR_VAL
-
Cause: Substring in
subor regular expression inregexis empty.
Runtime Error:STRG_ILLEGAL_PAR