REGEX in ABAP

Using REGEX (Regular Expressions) we can build smart codes. Regex is used for string processing and they are very fast.

In this example I'm formatting the names. My intention is to convert any name in the given format "Xxxxx Yyyyy". Using conventional ABAP programming this can get pretty messy as a name can be in any format. Thankfully REGEX helps a lot.

Example Name: PIERRE-LOUIS LEFÈVRE






The Output:











Another example with name: MARTIN LUTHER KING,JR.






The output:










Another example with name: TALLEGA Y PRADO






The output:











The Code : 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
*&---------------------------------------------------------------------*
*& Report  ZTEST_REGEX
*&
*&---------------------------------------------------------------------*
*&Demo program for www.abap-explorer.blogspot.com
*&---------------------------------------------------------------------*
 
REPORT  ztest_regex .
 
DATA: i_seltext TYPE STANDARD TABLE OF rsseltexts,
      wa_seltext TYPE rsseltexts.
DATA: l_off TYPE i,
      r_root TYPE REF TO cx_root,
      l_dummy TYPE c LENGTH 500,
      l_replacement TYPE string.
 
PARAMETERS: p_name TYPE c LENGTH 100 OBLIGATORY.
 
INITIALIZATION.
 
  wa_seltext-name = 'P_NAME'.
  wa_seltext-kind = 'P'.
  wa_seltext-text = 'Name'.
  APPEND wa_seltext TO i_seltext.
  CALL FUNCTION 'SELECTION_TEXTS_MODIFY'
    EXPORTING
      program                     = sy-repid
    TABLES
      seltexts                    = i_seltext
    EXCEPTIONS
      program_not_found           = 1
      program_cannot_be_generated = 2
      OTHERS                      = 3.
  IF sy-subrc <> 0.
* Implement suitable error handling here
  ENDIF.
 
START-OF-SELECTION.
  l_dummy = p_name.
 
  TRANSLATE l_dummy TO LOWER CASE.
  WHILE sy-subrc = 0.
    TRANSLATE l_dummy+l_off(1) TO UPPER CASE.
    FIND REGEX '(\<[a-z])' IN  l_dummy MATCH OFFSET l_off.
  ENDWHILE.
  WRITE: /1 'Formatted Name:',20 l_dummy.