ABAP中正则表达式的简单使用方法 (转老白BLOG)

在一个论坛上面看到有人在问正则表达式的问题,特举例简单说明一下。
另外,REPLACE也支持REGEX关键字。
最后:只能是ECC6或者更高版本才可以(ABAP supports POSIX regular expressions as of Release 7.00)

REPORT z_barry_test.

DATA: str TYPE string ,
result_tab TYPE match_result_tab ,
wa LIKE LINE OF result_tab.

*找出STRING里面的双字节字符
str = 'abc我啊adfsf们'.
FIND ALL OCCURRENCES OF REGEX '[^x00-xff]*' IN str RESULTS result_tab.
LOOP AT result_tab INTO wa.
WRITE / str+wa-offset(wa-length).
ENDLOOP.

*找出STRING里面的单字节字符
str = 'abc我啊adfsf们'.
FIND ALL OCCURRENCES OF REGEX '[x00-xff]*' IN str RESULTS result_tab.
WRITE / '-----'.
LOOP AT result_tab INTO wa.
WRITE / str+wa-offset(wa-length).
ENDLOOP.

*找出STRING里面的IP地址
str = 'IP1:172.16.32.12 IP2:192.168.1.1 '.
FIND ALL OCCURRENCES OF REGEX 'd+.d+.d+.d+' IN str RESULTS result_tab.
WRITE / '-----'.
LOOP AT result_tab INTO wa.
WRITE / str+wa-offset(wa-length).
ENDLOOP.

*找出STRING里面的***-********格式的电话号码
str = 'IP1:172.16.32.12 021-12345678 '.
FIND ALL OCCURRENCES OF REGEX 'd{3}-d{8}|d{4}-d{7}' IN str RESULTS result_tab.
WRITE / '-----'.
LOOP AT result_tab INTO wa.
WRITE / str+wa-offset(wa-length).
ENDLOOP.

*找出STRING里面的15/18位身份证号码
str = 'IP1:172.16.32.12 3722198003041234 '.
FIND ALL OCCURRENCES OF REGEX 'd{15}|d{18}' IN str RESULTS result_tab.
WRITE / '-----'.
LOOP AT result_tab INTO wa.
WRITE / str+wa-offset(wa-length).
ENDLOOP.

***使用CLASS的例子:
REPORT z_barry_test.
PARAMETERS: p_input TYPE string DEFAULT 'IP1:172.16.32.12 IP2:192.168.1.1 ' OBLIGATORY.
DATA: regex TYPE REF TO cl_abap_regex,
matcher TYPE REF TO cl_abap_matcher,
match TYPE c .
DATA: result_tab TYPE match_result_tab ,
wa LIKE LINE OF result_tab.
CREATE OBJECT regex
EXPORTING
pattern = 'd+.d+.d+.d+'
ignore_case = 'X'.
TRY.
CALL METHOD regex->create_matcher
EXPORTING
text = p_input
* table =
RECEIVING
matcher = matcher .
CATCH cx_sy_matcher .
ENDTRY.
TRY.
CALL METHOD matcher->match "是否完全匹配
RECEIVING
success = match.
CATCH cx_sy_matcher .
ENDTRY.
CALL METHOD matcher->find_all
RECEIVING
matches = result_tab.
LOOP AT result_tab INTO wa.
WRITE / p_input+wa-offset(wa-length).
ENDLOOP.
***SAP给的判断Email地址的例子***
PARAMETERS email TYPE c LENGTH 30 LOWER CASE DEFAULT 'sap@sap.com'.
DATA matcher TYPE REF TO cl_abap_matcher.
matcher = cl_abap_matcher=>create( pattern = 'w+(.w+)*@(w+.)+(w{2,4})'
ignore_case = 'X'
text = email ).
IF matcher->match( ) IS INITIAL.
MESSAGE 'Wrong Format' TYPE 'I'.
ELSE.
MESSAGE 'Format OK' TYPE 'I'.
ENDIF.
[@more@]

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/21277275/viewspace-1020060/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/21277275/viewspace-1020060/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值