说明意外的regexp_replace结果 [英] Explain unexpected regexp_replace result

查看:116
本文介绍了说明意外的regexp_replace结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为使用regexp_replace的练习,我在使用regexp_replace将一个字符串连接到另一个字符串的末尾时发现了意外的结果.我提出来的原因不仅在于找出原因,还在于让人们知道这种可能出乎意料的结果.

I found an unexpected result when using regexp_replace to concatenate a string on the end of another string, as an exercise in using regexp_replace to do it. I bring it up to not only figure out why, but to let folks know of this possibly unexpected result.

请考虑以下语句,其目的是在字符串"Note 1"的末尾添加"note 2".我的意图是将整行分组,然后将新字符串连接到末尾:

Consider this statement where the intent is to tack "note 2" on the end of string "Note 1". My intention was to group the entire line, then concatenate the new string to the end:

select regexp_replace('note 1', '(.*)', '\1' || ' note 2') try_1 from dual;

但是看看结果:

TRY_1               
--------------------
note 1 note 2 note 2

该笔记被重复两次!为什么?

The note gets repeated twice! Why?

如果我更改模式以包括行锚和行锚,则它会按预期工作:

If I change the pattern to include the start of line and end of line anchors, it works as expected:

select regexp_replace('note 1', '^(.*)$', '\1' || ' note 2') try_2 from  dual;

TRY_2        
-------------
note 1 note 2

为什么要有所作为?

请参阅下面的Politank-Z说明.如果我将第一个示例更改为使用加号(匹配前一个字符出现1个或多个),而不是星号(匹配前一个字符出现0个或多个),则我想添加它,按预期方式运行:

please see Politank-Z's explanation below. I wanted to add if I change the first example to use a plus (match 1 or more occurrences of the previous character) as opposed to the asterisk (for 0 or more occurrences of the previous character) it works as expected:

select regexp_replace('note 1', '(.+)', '\1' || ' note 2') try_3 from dual;

TRY_3        
-------------
note 1 note 2

推荐答案

按照 Oracle文档:

默认情况下,该函数在每次出现以下情况时都会返回source_char: 正则表达式模式替换为replace_string.

By default, the function returns source_char with every occurrence of the regular expression pattern replaced with replace_string.

其中的键是每次发生. .*匹配空字符串,Oracle regexp引擎首先匹配整个字符串,然后匹配以下空字符串.通过添加锚点,可以消除这种情况.或者,您可以根据链接的文档指定出现参数.

The key there is every occurence. .* matches the empty string, and the Oracle regexp engine is first matching the entire string, then the following empty string. By adding the anchors, you eliminate this. Alternatively, you could specify the occurrence parameter per the linked documentation.

这篇关于说明意外的regexp_replace结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆