Oracle REGEX_REPLACE 函数和捕获组
Oracle REGEX_REPLACE function and capture groups
我有一个字符串,我想将其从字符串序列转换为由连字符分隔的字符串序列。范例
200400116828 --> 2004-001168-28
对于要转换的字符串,输入的字符串必须遵循以下规则:
- Starts with a 1 or 2
- Followed by three digits
- Followed by 6 digits
- Followed by 2 digits
我使用 Regex 从输入字符串中提取上述组,以使用 Regex '^([12]\d{3})(\d{6})(\d{2})$
'
构建输出字符串
我设法使用以下查询让它工作:
Select REGEXP_REPLACE(
'200400116828','^([12]\d{3})(\d{6})(\d{2})$','--'
) from dual;
输出 - 2004-001168-28
但我对以下查询也有效但输出错误感到困惑:
Select REGEXP_REPLACE(
'200400116828','^([12]\d{3})(\d{6})(\d{2})$','--'
) from dual;
输出 - 20040-20041-20042
谁能解释一下第二个查询的输出,因为对我来说它与 RegEx 提供的不匹配。
正则表达式很好,您对替换模式感到困惑。
Oracle 正则表达式引擎是基于 POSIX 的,替换模式只支持从 1 到 9 的反向引用。不能被解析为反向引用的内容被解析为文字文本。
因此,--
被解析为第 1 组值,0-
,第 1 组值,1-
,第 1 组值,2
。
另请参阅 regexp_replace
documentation:
The replace_string
can contain up to 500 backreferences to subexpressions in the form \n
, where n
is a number from 1 to 9.
我有一个字符串,我想将其从字符串序列转换为由连字符分隔的字符串序列。范例
200400116828 --> 2004-001168-28
对于要转换的字符串,输入的字符串必须遵循以下规则:
- Starts with a 1 or 2
- Followed by three digits
- Followed by 6 digits
- Followed by 2 digits
我使用 Regex 从输入字符串中提取上述组,以使用 Regex '^([12]\d{3})(\d{6})(\d{2})$
'
我设法使用以下查询让它工作:
Select REGEXP_REPLACE(
'200400116828','^([12]\d{3})(\d{6})(\d{2})$','--'
) from dual;
输出 - 2004-001168-28
但我对以下查询也有效但输出错误感到困惑:
Select REGEXP_REPLACE(
'200400116828','^([12]\d{3})(\d{6})(\d{2})$','--'
) from dual;
输出 - 20040-20041-20042
谁能解释一下第二个查询的输出,因为对我来说它与 RegEx 提供的不匹配。
正则表达式很好,您对替换模式感到困惑。
Oracle 正则表达式引擎是基于 POSIX 的,替换模式只支持从 1 到 9 的反向引用。不能被解析为反向引用的内容被解析为文字文本。
因此,--
被解析为第 1 组值,0-
,第 1 组值,1-
,第 1 组值,2
。
另请参阅 regexp_replace
documentation:
The
replace_string
can contain up to 500 backreferences to subexpressions in the form\n
, wheren
is a number from 1 to 9.