You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ABAP中检查字符串是否包含大小写敏感的孤立单词?

Hey there! I get it—using CS (contains string) works for basic substring checks, but it doesn't cut it when you need to match isolated, case-sensitive exact words (like avoiding partial matches in TESTer or case variations like Test). Let's break down how to solve this in ABAP.

Core Idea: Use Regular Expression Word Boundaries

The key here is leveraging regex's word boundary anchors (\b) to ensure your target word isn't part of a longer word. A word boundary (\b) matches the position between a word character (letters, numbers, underscores) and a non-word character (spaces, punctuation, or the start/end of the string). Combined with case-sensitive matching, this will exactly match only the standalone TEST you want.

Option 1: Using the FIND REGEX Statement

This is a straightforward, inline way to check for matches:

CONSTANTS: lc_target_word TYPE string VALUE 'TEST',
           lc_regex_pattern TYPE string VALUE '\bTEST\b'.

DATA(your_string) = ls_structure-name.
DATA(is_match) = abap_false.

" Look for the case-sensitive word match
FIND REGEX lc_regex_pattern IN your_string 
  MATCH COUNT DATA(match_count) 
  CASE SENSITIVE.

IF match_count > 0.
  is_match = abap_true.
  " Add your counting logic here!
ENDIF.
  • \bTEST\b: Ensures TEST is surrounded by word boundaries (so no partial matches like TESTer).
  • CASE SENSITIVE: Guarantees only uppercase TEST is matched—Test or test will be ignored.

Option 2: Using the CL_ABAP_REGEX Class (More Flexible)

If you need to reuse the regex or handle more complex scenarios, the class-based approach is great:

CONSTANTS: lc_target_word TYPE string VALUE 'TEST'.

" Build the regex pattern dynamically (handy if your target word changes)
DATA(lc_regex_pattern) = |\b{lc_target_word}\b|.

" Create regex with case-sensitive flag
DATA(lo_regex) = NEW cl_abap_regex( 
  pattern = lc_regex_pattern
  flags = cl_abap_regex=>case_sensitive 
).

" Create matcher for your structure's name field
DATA(lo_matcher) = lo_regex->create_matcher( text = ls_structure-name ).

IF lo_matcher->find( ) = abap_true.
  " Match found—proceed with your counting
ENDIF.

Edge Cases to Note

  • If your target word ever includes regex special characters (like ., *, or ?), you'll need to escape them first using CL_ABAP_REGEX=>escape( ) to avoid unexpected behavior.
  • Word boundaries consider underscores (_) as word characters, so TEST_thing won't be matched (since _ is a word character, no boundary exists between TEST and _). If you need to treat underscores as separators, you'd adjust the regex to include them explicitly (e.g., (?:\b|_)TEST(?:\b|_)), but that's a niche case!

内容的提问来源于stack exchange,提问作者Cold_Class

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 22:02:29