简体   繁体   English

获取 FIND OF REGEX 语句的子匹配项

[英]Get submatches of FIND OF REGEX statement

I would not only check a string for any occurrence of a substring using regex but also get the result ("45" in my example) of the found regex.我不仅会使用正则表达式检查字符串是否出现任何子字符串,而且还会获得找到的正则表达式的结果(在我的示例中为“45”)。

I tried:我试过:

 DO.
    FIND FIRST OCCURRENCE OF REGEX '[$][0-9]+[$]' IN 'safmaoigrevnwnfuwifhd$45$sdffge' 
        MATCH OFFSET lv_match_offset MATCH LENGTH lv_match_len 
        SUBMATCHES DATA(s1) DATA(s2) DATA(s3).
    IF sy-subrc = 0.
      " I expected s2 to contain the value between the "$"
      lv_match-value = s2.
      " remove found substring from annotation name for next loop
      lv_annotation_name = lv_annotation_name+lv_match_offset(lv_match_len).
    ELSE.
      EXIT.
    ENDIF.
  ENDDO.

s1, s2 and s3 are always initial but why? s1、s2 和 s3 总是初始的,但为什么呢? I thought that they would contain the value of the found regex, eg "$", "45", "$".我认为它们将包含找到的正则表达式的值,例如“$”、“45”、“$”。 What am I doing wrong?我究竟做错了什么? Is there a more elegant way than my approach?有没有比我的方法更优雅的方法?

Following Sandra's suggestion I changed the code to按照 Sandra 的建议,我将代码更改为

FIND ALL OCCURRENCES OF REGEX lv_index_regex IN lv_annotation_name RESULTS lt_matches. 

Note that FIND ALL ... MATCHES does not exist, I assumed Sandra meant "RESULTS".请注意, FIND ALL ... MATCHES不存在,我认为 Sandra 的意思是“结果”。 lt_matches then contains the itab submatches but its always empty.... lt_matches则包含ITAB submatches ,但它总是空....

The word SUBMATCHES in the statement FIND [FIRST OCCURRENCE OF] REGEX is used to extract directly the registered subgroups (...) (AKA submatches) of the match into variables.语句FIND [FIRST OCCURRENCE OF] REGEX的单词SUBMATCHES用于将匹配的注册子组(...) (AKA 匹配(...)直接提取到变量中。

So, just put some parentheses around each of them:所以,只需在它们周围加上一些括号:

FIND FIRST OCCURRENCE OF REGEX '([$])([0-9]+)([$])' 
    IN 'safmaoigrevnwnfuwifhd$45$sdffge' 
    MATCH OFFSET lv_match_offset 
    MATCH LENGTH lv_match_len 
    SUBMATCHES DATA(s1) DATA(s2) DATA(s3).

Note that your code will do an endless loop, but that's another question (it will be easier to find all matches at a time with FIND ALL OCCURRENCES OF REGEX ... RESULTS itab and loop at the internal table, each line being one match, and each line also contains the list of the submatches).请注意,您的代码将执行无限循环,但这是另一个问题(使用FIND ALL OCCURRENCES OF REGEX ... RESULTS itab并在内部表中循环,每次查找所有匹配项会更容易,每一行都是一个匹配项,并且每一行还包含子匹配列表)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM