Check if string contains an isolated word

Viewed 285

When I'm searching for a word in a string, I usually do it something like this:

CONSTANTS:
      lc_word TYPE string VALUE 'TEST',
      .

IF ls_structure-name CS lc_word.
      "count( ).
ENDIF.

But this time I only want it to be true if the word is isolated and case sensitive.
For example:

  • TESTer, Test should not count
  • TEST, lol TEST, TEST yourself, hi TEST yourself should count

Does someone have an idea how to do that?

2 Answers

You can use a regex check:

FIND REGEX '(\s|^)TEST(\s|$)' IN ls_structure-name.

IF sy-subrc EQ 0.
      "count( ).
ENDIF.

It checks for the following pattern:

  • Whitespace or the beginning of the string
  • 'test'
  • Whitespace or the end of the string

You can split your sentence into table, then check if it exists in tale. Like this:

DATA: lv_string TYPE string VALUE 'One two TEST three',
      lv_var    TYPE string VALUE 'TEST',
      lv_count  TYPE i.


SPLIT lv_string AT space INTO TABLE DATA(lt_string).
IF line_exists( lt_string[ table_line = lv_var ] ).
  lv_count = lv_count + 1.
ENDIF.
WRITE: / lv_count.
Related