Entering content frame

Function documentation Regular Expressions in Routines Locate the document in its SAP Library structure

Use

You can use regular expressions in routines.

A regular expression (abbreviation: RegExp or Regex) is a pattern of literal and special characters which describes a set of character strings. In ABAP, you can use regular expressions in the FIND and REPLACE statements, and in classes CL_ABAP_REGEX and CL_ABAP_MATCHER. For more information, see the ABAP key word documentation in the ABAP Editor. This documentation describes the syntax of regular expressions and you can test regular expressions in the ABAP Editor.

Example

This section provides sample code to illustrate how you can use regular expressions in routines.

For Inserting ‘Thousand’ Separators:

This graphic is explained in the accompanying text

* test 1: insert thous. sep
 
l_input = '12345678'.
 l_regex = '([0-9])(?=([0-9]{3})+(?![0-9]))'.
l_new = '$1,'.

REPLACE
* FIRST OCCURRENCE OF
  
ALL OCCURRENCES OF
  REGEX l_regex
  IN l_input WITH l_new
* REPLACEMENT OFFSET off
* REPLACEMENT LENGTH len
* REPLACEMENT COUNT cnt
.

For Converting the US Date Format into the German Date Format:

This graphic is explained in the accompanying text

* Test 2: Date USA->Dt
 
l_input = '6/30/2005'.
 l_regex = '([01]?[0-9])/([0-3]?[0-9])/'.
 l_new = '$2.$1.'.

REPLACE
* FIRST OCCURRENCE OF |
  
ALL OCCURRENCES OF
  REGEX l_regex
  IN l_input WITH l_new
* REPLACEMENT OFFSET off
* REPLACEMENT LENGTH len
* REPLACEMENT COUNT cnt
.

For Converting an External Format into the Internal Format:

This graphic is explained in the accompanying text

* convert data external to internal

DATA: matcher TYPE REF TO cl_abap_matcher,
      submatch1   TYPE string,
      submatch2 type string,
      match type c.

l_input = '6/30/2005'.

clear l_new.

l_regex = '([01]?)([0-9])/([0-3]?)([0-9])/([0-9]{4})'.

matcher = cl_abap_matcher=>create( pattern     = l_regex
                                   text        = l_input ).

match = matcher->match( ).

TRY.
CALL METHOD MATCHER->GET_SUBMATCH
  EXPORTING
    INDEX    = 1
  RECEIVING
    SUBMATCH = submatch1.
    .
 CATCH CX_SY_MATCHER .
ENDTRY.

TRY.
CALL METHOD MATCHER->GET_SUBMATCH
  EXPORTING
    INDEX    = 3
  RECEIVING
    SUBMATCH = submatch2.
    .
 CATCH CX_SY_MATCHER .
ENDTRY.


if submatch1 is initial.
  if submatch2 is initial.
    l_new = '$5\0$4\0$2'.
  else.
     l_new = '$5$3$4\0$2'.
  endif.
else.
  if submatch2 is initial.
    l_new = '$5\0$4$1$2'.
  else.
     l_new = '$5$3$4$1$2'.
  endif.
endif.

REPLACE
* FIRST OCCURRENCE OF |
  
ALL OCCURRENCES OF
  REGEX l_regex
  IN l_input WITH l_new
* REPLACEMENT OFFSET off
* REPLACEMENT LENGTH len
* REPLACEMENT COUNT cnt
.

 

Leaving content frame