Strings, String Templates and Regular Expressions
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
Nearly every ABAP program handles text: it builds a message for a user, cuts an identifier into parts, checks that a code looks
right, or removes stray blanks from a value that was typed in. This page shows the tools ABAP offers for that work. The newest
and most readable one is the string template, a piece of text between vertical bars in which values can be inserted. Next come
the built-in string functions, which return a new text from an old one, and then the older statements such as CONCATENATE
and SPLIT, which you will meet in almost every existing program. The page ends with regular expressions, a compact way of
describing a pattern of characters. It is written against Standard ABAP release 8.16 and ABAP for Cloud Development
release 9.20 (2608). String templates, string functions and regular expressions work in ABAP Cloud and in classic, Standard
ABAP only, code on premise; for the older statements, check the keyword documentation of ABAP Cloud before using one in
ABAP Cloud code. After reading, you can format a summary line from several values, cut and clean text, and test or extract
parts of it with a pattern. The examples use the Expense claims running example (the tables ZEXP_CLAIM and ZEXP_ITEM)
and simple generic values.
Before you read
-
Data Types and Data Objects: the types
candstring, and how a variable is declared. -
Expressions, Operators and Assignments: how a value is converted when it is stored in a variable of another type.
-
Program Types and Structure: where statements are written.
Key terms
-
String: a text of any length whose size grows and shrinks as needed (type
string). -
Text field: a text of fixed length (type
c), padded with blanks on the right. -
String template: a text between vertical bars that can contain expressions in curly braces.
-
String function: a built-in function that takes a text and returns a new text or a number, such as
strlen. -
Regular expression: a pattern that describes which texts match, for example "three digits".
-
Offset and length: a way to address part of a text by its start position and number of characters.
Two kinds of text and their literals
ABAP has two everyday types for text. A text field (type c) has a fixed length chosen when it is declared; shorter values
are padded with blanks and the blanks on the right are ignored in comparisons. A string (type string) has no fixed length
and keeps every character you put in, including trailing blanks. A text written in the program, a literal, takes its type
from its quotes. Text between single quotes, such as 'abc', is a text field literal; text between backquotes, such as
, is a string literal and keeps trailing blanks. A string template, described next, always produces a string.abc
For new code, prefer the type string for text of changing length and use fixed-length fields only where a data model
requires them, for example a table column of type c.
String templates
A string template is written between vertical bars. Everything inside is literal text, except what is in curly braces: there you write an expression, and its value is converted to text and inserted. The expression can be a variable, a calculation, a method call or a function call. Write a space after the opening brace and before the closing brace, as in the examples.
DATA(name) = `Ada`.
DATA(count) = 3.
DATA(greeting) = |Hello { name }, you have { count } open claims, { count * 10 } EUR pending.|.
This example runs in the local playground, where greeting holds Hello Ada, you have 3 open claims, 30 EUR pending. Source:
ABAP Keyword Documentation: String Templates
To write a character that has a special meaning inside a template, put a backslash before it: \| for a bar, \{ and
\} for braces and \\ for a backslash. The sequences \n, \r and \t stand for a line feed, a carriage return
and a tab.
Formatting options
After the expression, a template can say how the value is to be shown, with the form { value OPTION = setting }. Several
options can follow each other. The most useful ones are:
| Option | What it controls |
|---|---|
|
Minimum length of the result, whether the value sits at the left, the right or the centre, and the character used to fill the free space. |
|
Upper case or lower case. |
|
Where a minus sign is shown, and whether a plus sign is shown for positive numbers. |
|
Number of decimal places, the exponent of a floating-point number, and whether a zero is shown. |
|
How a number, date, time or time stamp is written, for example according to the user’s settings or in a fixed format. |
|
The number of decimal places that belongs to a currency key. |
|
How a number is written (for example plain, scientific or with the sign at the end), XML Schema formats, and country-specific formats together with a time zone. |
The exact list of settings for each option, and which ones apply to which types, is in the keyword documentation of string
templates (see the source below). The example below formats one line of a claim summary. It uses WIDTH, ALIGN and DECIMALS; in the local
playground the alignment is not applied (the result is left aligned), so run this one on an SAP system.
CLASS zcl_exp_summary DEFINITION PUBLIC FINAL CREATE PUBLIC.
PUBLIC SECTION.
CLASS-METHODS summary_line
IMPORTING claim_id TYPE string
employee TYPE string
amount TYPE decfloat34
currency TYPE string
RETURNING VALUE(line) TYPE string.
ENDCLASS.
CLASS zcl_exp_summary IMPLEMENTATION.
METHOD summary_line.
line = |Claim { claim_id WIDTH = 8 ALIGN = LEFT }| &&
| { to_upper( employee ) }| &&
| { amount DECIMALS = 2 ALIGN = RIGHT WIDTH = 10 } { currency }|.
ENDMETHOD.
ENDCLASS.
This listing requires an SAP system; not run here. Source: ABAP Keyword Documentation: String Templates
The operator && joins two texts. Because one template may be broken over several lines with it, long messages stay readable.
Calling summary_line( claim_id = `C-1001` employee = `Ada Lovelace` amount = '125.5' currency = `EUR` ) returns a line
that starts with the claim number, then the name in capitals, then the amount with two decimals, right-aligned in ten places,
and the currency.
String functions
A string function is called like a method: its name, then the arguments in parentheses. It returns a value and does not change its input, so it can be used directly inside a template, a condition or an assignment. The functions below are the ones needed most often.
| Function | What it returns |
|---|---|
|
The number of characters. For a text field the blanks on the right are not counted. |
|
The text in upper or in lower case. |
|
The text with leading and trailing blanks removed and each run of inner blanks cut to one. The optional |
|
The part of the text that starts after |
|
The text with the old piece replaced; |
|
The position of the first match, or -1 when there is none. It also accepts a |
|
A truth value for use in conditions; |
|
The text backwards, and the text written |
|
The rows of a table of texts joined into one string; an optional |
A function that returns text can be given as an argument to another one, so to_upper( condense( raw ) ) first cleans and
then capitalises. The keyword documentation lists the full set, including the functions for mixed-case names and for
escaping special characters.
Offset and length
A part of a text can also be addressed directly by its position, written text+off(len): code+2(3) is the three
characters that follow the first two. This form is short, but the position must lie inside the text, so the length of a string
has to be checked first. The functions such as substring read more clearly; prefer them in new code.
Classic string statements
Long before the functions existed, ABAP changed texts with statements, and every older program is full of them. They are still valid, and some do work that no function does, so they are worth knowing. Each one works on a variable in place.
-
CONCATENATE a b c INTO resultjoins texts;SEPARATED BYinserts a separator between them. The template|{ a }{ b }|or the operator&&does the same in an expression. -
SPLIT text AT ',' INTO TABLE partscuts a text at every separator and puts the pieces in the rows of an internal table. -
CONDENSE textremoves leading blanks and shortens inner runs of blanks to one;NO-GAPSremoves the inner blanks as well. -
TRANSLATE text TO UPPER CASEchanges the case, andTRANSLATE text USING 'ab12'replaces eachabyband each1by2. -
SHIFT text LEFT BY 2 PLACESmoves the content and drops characters that fall out;SHIFT text LEFT DELETING LEADING '0'removes leading zeros. -
FINDandREPLACEsearch and change a text, with a plain piece of text or with a regular expression. They set the system fieldsy-subrcto 0 when something was found, andFIND ... MATCH OFFSET ... MATCH LENGTH ...returns where.
Because these statements change the variable itself, keep a copy first if the original is needed later.
DATA lt_parts TYPE STANDARD TABLE OF string WITH EMPTY KEY.
SPLIT `C-1001;Ada Lovelace;125.50;EUR` AT ';' INTO TABLE lt_parts.
DATA(joined) = concat_lines_of( table = lt_parts sep = ` | ` ).
DATA(raw) = ` too many blanks `.
CONDENSE raw.
DATA(upper) = to_upper( raw ).
This runs in the local playground: joined holds C-1001 | Ada Lovelace | 125.50 | EUR, and upper holds TOO MANY BLANKS. Source:
ABAP Cheat Sheet: String Processing
Regular expressions
A regular expression, or pattern, describes a set of texts instead of one text. ABAP supports the PCRE flavour of regular expressions, the same family that many other languages use, so most patterns learned elsewhere work, with ABAP-specific restrictions. The building blocks that cover most needs are:
-
.is any one character,\da digit,\sa white-space character such as a blank, and\wa letter, digit or underscore. -
[A-Z]is one character from a range;[^0-9]is one character that is not a digit. -
*means "zero or more",+"one or more",?"zero or one" and{3}"exactly three" of what comes before. -
^and$mean the start and the end of the text;|means "or"; parentheses group a part and remember what it matched.
Patterns are written as ordinary text literals, so use the single quote or the backquote and keep the backslashes as they are.
The functions find, replace, matches, contains and count and the statements FIND and REPLACE take the pattern
as shown below:
the functions in a pcre argument, the statements after the addition PCRE. In a replacement text, $1 stands for what the
first pair of parentheses matched, and $0 for the whole match.
DATA(claim_id) = `C-1001`.
IF matches( val = claim_id pcre = `C-\d{4}` ).
" the whole text is a claim number
ENDIF.
DATA(note) = `Taxi 12.50 and hotel 80.00`.
DATA(masked) = replace( val = note pcre = `\d+\.\d\d` with = `<amount>` occ = 0 ).
FIND PCRE `(\w+)\s+(\d+\.\d\d)` IN note SUBMATCHES DATA(item) DATA(price).
This listing runs in the local playground: the condition is true, masked holds Taxi <amount> and hotel <amount>, item holds
Taxi and price holds 12.50. Source:
ABAP Cheat Sheet: Regular Expressions
Keep patterns short and test them on a few real values, including values that must not match: a pattern that is too loose accepts bad data, and one that is too strict rejects good data.
Choosing a tool
Older material you may meet
Books and programs written before string templates and inline declarations existed use a different style. Texts were joined with CONCATENATE, formatted with
WRITE ... TO and edited with SHIFT and CONDENSE, and positions were taken with text+off(len). Variables were declared
in a block at the top, so a helper variable for each intermediate text was normal. Today the string template replaces most
joining and formatting, the string functions return values that can be nested without helper variables, and DATA( )
declares a result at the place where it is first used. Older regular-expression examples may use the POSIX flavour, written
with the regex parameter of the functions or the REGEX addition of the statements; that flavour is obsolete, and pcre and PCRE are its replacement. The classes
cl_abap_regex and cl_abap_matcher also work with PCRE. Old code still runs, so you do not have to rewrite
it, but read each statement against the current documentation before copying it into new code.
Summary
-
A string template, written between vertical bars, inserts the value of any expression in curly braces and can format it with options such as
WIDTH,ALIGN,DECIMALSandCASE. -
A string function returns a new value and leaves its input unchanged, so it can be nested inside other expressions.
-
The statements
CONCATENATE,SPLIT,CONDENSE,TRANSLATE,SHIFT,FINDandREPLACEchange a variable in place and fill most older programs. -
A regular expression describes a pattern of characters; it is passed as the
pcreargument of the functions and thePCREaddition of the statements, and$1in a replacement refers to a remembered part. -
Type
stringkeeps trailing blanks and has no fixed length; typechas a fixed length and ignores trailing blanks.
Try it
To do this by hand, follow the guide Data Types, Strings and String Templates: it declares variables, converts values and builds strings and string templates.