Regular Expressions or RegEx are very powerful and useful when working with Text literals. Check out how RegEx can be used in ABAP
What is Regular Expression
Regular Expression, better known as RegEx, is a sequence of character string which can be used to Search or Replace in a string or character literals. The concept of RegEx is around for a long time. RegEx Processor will understand meaning of each character within the RegEx string and would perform desired operation on the target string.
How to Use Regex in ABAP
When you want to use the RegEx, you can simply add additional keywords REGEX in the FIND or REPLACE statements.
FIND ALL OCCURRENCES OF REGEX '[A-Z]' IN 'ABCDE12345'.
REPLACE ALL OCCURRENCES OF REGEX '[A-Z]' IN lv_input WITH space.
When to use RegEx
RegEx should be used when you are looking for complex patterns. Like Searching for all numbers or alphabets or special characters or validating Email etc.
Lets take this simple example:
FIND 'A' IN 'ABCDE12345' MATCH COUNT sy-tabix. WRITE: sy-tabix.
Now if you want to find all alphabets in the string. If you use normal search without RegEx, you would end up searching for each of the 26 characters in the string within a loop. Using RegEx, it would be easy to search like:
Find using RegEx
FIND ALL OCCURRENCES OF REGEX '[A-Z]' IN 'ABCDE12345' MATCH COUNT sy-tabix. WRITE: sy-tabix.
Using Class CL_ABAP_REGEX and CL_ABAP_MATCHER
CL_ABAP_REGEX and CL_ABAP_MATCHER classes are available from ABAP Release 640. You can use the _REGEX class to create a RegEx . Using the RegEx object get the Matcher object. Use the Matcher object to check if the values are being matched or not.
Re-writing the example RegEx again using CL_ABAP_REGEX
Usage of Regex Utility Class CL_ABAP_REGEX
DATA: regex TYPE REF TO cl_abap_regex, " Regex Object matcher TYPE REF TO cl_abap_matcher, " Matcher Object value_to_check TYPE string. * value_to_check = '12345677'. * Instntiate Regex CREATE OBJECT regex EXPORTING pattern = '[A-Z]' ignore_case = abap_true. * Create the Matcher matcher = regex->create_matcher( text = value_to_check ). * Match not found, invalid IF matcher->match( ) = 'X'. WRITE: 'Its a match'. ELSE. WRITE: 'Not a match'. ENDIF.
Demo Program DEMO_REGEX_TOY
As name suggested, you can use the program DEMO_REGEX_TOY to play with the RegEx. You input the RegEx, Input the source text, select the options and it would highlight the results.
In Next articles, I would demo few more RegEx.