How to find any non-digit characters using RegEx in ABAP

Viewed 4366

I need a Regular Expression to check whether a value contains any other characters than digits between 0 and 9.

I also want to check the length of the value.

The RegEx I´ve made: ^([0-9]\d{6})$

My test value is: 123Z45 and 123456

The ABAP code:

FIND ALL OCCURENCES OF REGEX '^([0-9]\d{6})$' IN L_VALUE RESULTS DATA(LT_RESULTS).

I´m expecting a result in LT_RESULTS, when I´m testing the first test value '123Z45', because there is a non-digit character.

But LT_RESULTS is in nearly every test case empty.

3 Answers

Your expression ^([0-9]\d{6})$ translates to:

  • ^ - start of input
  • ( - begin capture group
    • [0-9] - a character between 0 and 9
    • \d{6} - six digits (digit = character between 0 and 9)
  • ) - end capture group
  • $ - end of input

So it will only match 1234567 (7 digit strings), not 123456, or 123Z45.

If you just need to find a string that contains non digits you could use the following instead: ^\d*[^\d]+\d*$

  • * - previous element may occur zero, one or more times
  • [^\d] - ^ right after [ means "NOT", i.e. any character which is not a digit
  • + - previous element may occur one or more times

Example:

const expression = /^\d*[^\d]+\d*$/;
const inputs = ['123Z45', '123456', 'abc', 'a21345', '1234f', '142345'];

console.log(inputs.filter(i => expression.test(i)));

You can also use this character class if you want to extract non-digit group:

DATA(l_guid) = '0074162D8EAA549794A4EF38D9553990680B89A1'.

DATA(regx) = '[[:alpha:]]+'.

DATA(substr) = match( val   = l_guid
                      regex = regx
                      occ   = 1 ).

It finds a first occured non-digit group of characters and shows it.

If you want to just check if they are exists or how much of them reside in your string, count built-in function is your friend:

DATA(how_many) = count( val = l_guid regex = regx ).

DATA(yes) = boolc( count( val = l_guid regex = regx ) > 0 ).

Match and count exist since ABAP 7.50.

If you don't need a Regular Expression for something more complex, ABAP has some nice comparison operators CO (Contains Only), CA, NA etc for you. Something like:

IF L_VALUE CO '0123456789' AND STRLEN( L_VALUE ) = 6.
Related