如何在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: EnsuresTESTis surrounded by word boundaries (so no partial matches likeTESTer).CASE SENSITIVE: Guarantees only uppercaseTESTis matched—Testortestwill 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 usingCL_ABAP_REGEX=>escape( )to avoid unexpected behavior. - Word boundaries consider underscores (
_) as word characters, soTEST_thingwon't be matched (since_is a word character, no boundary exists betweenTESTand_). 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

