Check if a String is Numeric in SAP ABAP
To check whether a string contains only numeric values, you can use several methods depending on your ABAP version.
1. Using CONDENSE
+ IS NUMERIC
(Simple & Effective)
DATA: lv_string TYPE string VALUE '12345'.
CONDENSE lv_string NO-GAPS. " Remove spaces
IF lv_string IS NUMERIC. WRITE: 'String is numeric'.ELSE. WRITE: 'String is not numeric'.ENDIF.
- Works for integer numbers only (no decimals, signs, or special characters).
- Leading/trailing spaces are ignored using
CONDENSE
.
2. Using FIND REGEX
(Supports Decimals, Negative Numbers)
DATA: lv_string TYPE string VALUE '-123.45'.
IF lv_string CP '-*([0-9]+(\.[0-9]+)?)'. WRITE: 'String is numeric'.ELSE. WRITE: 'String is not numeric'.ENDIF.
- Supports: Negative numbers (
-
), decimals (.
). - More flexible than
IS NUMERIC
.
3. Using cl_abap_matcher
(ABAP 7.40+)
DATA: lv_string TYPE string VALUE '12345', lo_matcher TYPE REF TO cl_abap_matcher.
lo_matcher = cl_abap_matcher=>create( pattern = '^\d+$' ).IF lo_matcher->match( text = lv_string ). WRITE: 'String is numeric'.ELSE. WRITE: 'String is not numeric'.ENDIF.
- Best for strict numeric checks (digits only).
4. Using TRANSLATE
+ Loop for Character Validation
DATA: lv_string TYPE string VALUE '12345', lv_char TYPE c LENGTH 1, lv_valid TYPE abap_bool VALUE abap_true, lv_offset TYPE i.
DO STRLEN( lv_string ) TIMES. lv_char = lv_string+lv_offset(1). IF lv_char < '0' OR lv_char > '9'. lv_valid = abap_false. EXIT. ENDIF. lv_offset = lv_offset + 1.ENDDO.
IF lv_valid = abap_true. WRITE: 'String is numeric'.ELSE. WRITE: 'String is not numeric'.ENDIF.
- Manually checks each character.
- Best for older ABAP versions (before 7.40).
Best Method to Use?
Method | Best For | Supports Decimal? | Supports Negative? |
---|---|---|---|
IS NUMERIC | Simple integer checks | ❌ | ❌ |
FIND REGEX | Flexible & fast | ✅ | ✅ |
cl_abap_matcher | Best for strict regex checks (ABAP 7.40+) | ✅ | ✅ |
TRANSLATE + LOOP | For older ABAP versions | ❌ | ❌ |