Application Development and Automation Discussions
Join the discussions or start your own on all things application development, including tools and APIs, programming models, and keeping your skills sharp.
cancel
Showing results for 
Search instead for 
Did you mean: 
Read only

Using negation in Regular expression

Former Member
0 Likes
1,628

Hi All,

I need to write a pattern using regular expression where the word does not end with some characters.

Suppose I have a word ZBH_MM_CHECK, the word should start with ZBH I can write the pattern as ^ZBH[_][A-Z]{2}[_]\w  . If the end of the word should not contain _X how should we write such pattern. Here I should check that the word should not end with _X using regular expression. ZBH_MM_CHECK_X is invalid but ZBH_MM_CHECK is valid. I tried using (?!_X)$ at the end but failed. Please suggest.

Thanks in Advance.

3 REPLIES 3
Read only

former_member201285
Active Participant
0 Likes
847

This sample code might help:

    DATA: suffix_to_check(2) TYPE c VALUE '_X',
        pattern(50) TYPE c VALUE 'ZBH_MM_CHECK_X',
        offset TYPE i.

  offset = strlen( pattern ) - strlen( suffix_to_check ).

  IF pattern+offset = suffix_to_check.

    WRITE: 'Not valid!'.

  ENDIF.

Read only

hendrik_brandes
Contributor
0 Likes
847

Hello,

I would suggest, you make an expression like this:

(^ZBH[_][A-Z]{2}[_]\w{5})(_X)?

Then you will have the _X in the second subgroup, if the expression match otherwiuse you have just one subgroup.

Try your expression within the report DEMO_REGEX_TOY.

Kind regards,

Hendrik

Read only

Former Member
0 Likes
847

While using regex, character negation can be done but not word negation.

Alternative would be to check value stored in substring like this.

DATA lv_substr TYPE string.

FIND REGEX '^ZBH_[A-Z]{2}_\w+_(.*)'

  IN 'ZBH_MM_CHECK_X'

  SUBMATCHES lv_substr .

IF sy-subrc EQ 0 AND lv_substr NE 'X'.

  "match

ENDIF.