Replace String

After searching, the replacement of substrings in character strings is the most important application of regular expressions. When replacing, the found locations of a search (or the substrings that match a regular expression), are replaced by one or more different character strings. In ABAP, the replacement is realized using regular expressions with the addition REGEX of the statement REPLACE.

In contrast to normal text replacements, when regular expressions are used, operators can be used in the replacement text that refer to the relevant found location.

Operators for replacement texts

The following operators can be specified in the replacement text. These operators are made up of the special characters $, &, ` and ´. The special characters can made into literal characters by the prefix \.

Addressing the whole found location

The operators $0 and $& can be entered in the replacement text as placeholders for the whole current found location.

Example

After replacement, text has the content Yeah Yeah Yeah!.

DATA: text TYPE string.

text = `Yeah!`.

REPLACE REGEX `\w+` IN text WITH `$0 $0 $&`.

Addressing the registers of subgroups

The operators $1, $2, $3, ... can be used in the replacement text as placeholders for the character strings stored in the registers of subgroups for the current found location. If the n-th subgroup is not available, or it is not supplied with a value in the match, the corresponding operator $n is replaced by the empty character string.

Example

After replacement, text has the content Roll'n'Rock.

DATA: text TYPE string.

text = `Rock'n'Roll`.

REPLACE REGEX `(\w+)(\W\w\W)(\w+)` IN text WITH `$3$2$1`.

Addressing the text before the found location

The operator $` can be used in the replacement text as a placeholder before the current found location. If several found locations are replaced using REPLACE ALL OCCURRENCES, $` contains the unchanged text from the beginning of the text to the start of the found location, for every found location.

Example

After replacement, text has the content again and again.

DATA: text TYPE string.

text = `again and`.

REPLACE REGEX 'and' IN text WITH '$`$0 $`'.

Addressing the text after the found location

The operator $' can be used in the replacement text as a placeholder for the whole text after the current found location.

Example

After replacement, text has the content and again.

DATA: text TYPE string.

text = `again and`.

REPLACE REGEX `again ` IN text WITH `$' $0`.