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.
REPORT z_regex.
DATA: l_input TYPE string,
l_regex TYPE string,
l_new TYPE string.
* Example 1: Insert thousand separator
l_input = '12345678'.
l_regex = '([0-9])(?=([0-9]{3})+(?![0-9]))'.
l_new = '$1,'.
WRITE: / 'Before:', l_input. "12345678
REPLACE
ALL OCCURRENCES OF
REGEX l_regex
IN l_input WITH l_new.
WRITE: / 'After:', l_input. "12,345,678
* Example 2: Convert date in US format to German format
l_input = '6/30/2005'.
l_regex = '([01]?[0-9])/([0-3]?[0-9])/'.
l_new = '$2.$1.'.
WRITE: / 'Before:', l_input. "6/30/2005
REPLACE
ALL OCCURRENCES OF
REGEX l_regex
IN l_input WITH l_new.
WRITE: / 'After:', l_input. "30.6.2005
* Example 3: Convert external date in US format to internal date
DATA: matcher TYPE REF TO cl_abap_matcher,
submatch1 TYPE string,
submatch2 TYPE string,
match TYPE c.
l_input = '6/30/2005'.
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$2\0$4'.
ELSE.
l_new = '$5\0$2$3$4'.
ENDIF.
ELSE.
IF submatch2 IS INITIAL.
l_new = '$5$1$2\0$4'.
ELSE.
l_new = '$5$1$2$3$4'.
ENDIF.
ENDIF.
WRITE: / 'Before:', l_input. "6/30/2005
REPLACE
ALL OCCURRENCES OF
REGEX l_regex
IN l_input WITH l_new.
WRITE: / 'After:', l_input. "20050630
No comments:
Post a Comment