Monday, January 6, 2014

Searching within the strings in ABAP

There are few possibilities of how to manage searching within the strings variables in ABAP:

1. The classic way is to use comparison operators for character-like data types. These are following operators which can be used for character-like operands:
CO – Contains Only
CN – Contains NOT Only
CA – Contains Any
NA – Contains NOT Any
CS – Contains String
NS – Contains NOT String
CP – Contains Pattern
NP – NO Pattern

Following wildcards can be used:
* represents any character string,
+ represents any character

To check if string contains value CA followed by underscore; then followed by any combination of 2 characters; then again underscore; then  combination of any 10 characters and finally 10 spaces; would be represented like (this represents Transfer structure between source system and BW - data element RSTRANSTRU):

if l_transtru cp 'CA_++_++++++++++           '.

2. Predicate Functions is other possibility. It basically does the same as above mentioned comparison operators. There are 2 sorts of the fusions:
2.1 contains* / contains_any*
2.1.1. ... contains( val = text  sub|start|end = substring [case = case] [off = off] [len = len] [occ = occ] ) ...

2.1.2. ... contains( val = text regex = regex [case = case] [off = off] [len = len] [occ = occ] ) ...

2.1.3. ... contains_any_of( val = text sub|start|end = substring [off = off] [len = len] [occ = occ] ) ...

2.1.4. ... contains_any_not_of( val = text sub|start|end = substring [off = off] [len = len] [occ = occ] ) ...
2.1. matches [matches( val = text regex = regex [case = case] [off = off] [len = len] ) ...] - compares a search area defined by off and len of the argument text to the regular expression specified in regex and returns the relevant truth value

3. Other possibility much more modern is to use regular expressions. Regular expressions statement REGEX can be used as addition of FIND and REPLACE statements for searching in character strings. More complex regular expression can be handled by classes CL_ABAP_REGEX and CL_ABAP_MATCHER. To model precise regular expression that you need for your development see ABAP report DEMO_REGEX_TOY or DEMO_REGEX. Regular expression is huge topic which deserves separate post. So for time being I’m just providing documents on SDN related to that:

No comments: