regexp_replace oracle 的替换部分
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15799548/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Replacement portion of regexp_replace oracle
提问by Raj A
I have a regexp_replace where I want to have the replacement portion to be sub part of the replaced string.. In below example /2 should always give the first part i.e MON For example
我有一个 regexp_replace,我想让替换部分成为替换字符串的子部分。在下面的例子中,/2 应该总是给出第一部分,即 MON 例如
SELECT REGEXP_REPLACE('Test MON 234','^(.*? )(MON|FRI|SAT|SUN).*$', '') FROM dual;
==> Test MON
SELECT REGEXP_REPLACE('QA FRI 111','^(.*? )(MON|FRI|SAT|SUN).*$', '') FROM dual;
should give ==> QA MON
回答by collapsar
the trivial answer:
微不足道的答案:
SELECT REGEXP_REPLACE('Test MON 234','^(.*? )(MON|FRI|SAT|SUN).*$', 'MON') FROM dual;
SELECT REGEXP_REPLACE('QA FRI 111','^(.*? )(MON|FRI|SAT|SUN).*$', 'MON') FROM dual;
the less trivial answer: extract the frozen part of your replacement string from the regexp.
不太重要的答案:从正则表达式中提取替换字符串的冻结部分。
SELECT REGEXP_REPLACE('^(.*? )(MON|FRI|SAT|SUN).*$', '^[^(]*\([^(]*\(([^)|]+).*$', '') FROM dual;
note the assumptions of this solution: - you want precisely the first alternative of the second capture group. - no nested capture groups - no escaped capture group delimiters
请注意此解决方案的假设: - 您恰好需要第二个捕获组的第一个选择。- 没有嵌套的捕获组 - 没有转义的捕获组分隔符
for anything more complicated (in fact, for this use case, too) you might wish to consider obtaining the frozen replacement from whatever source determines that and not by extracting it from the regex pattern. otherwise there will be a code maintenance nightmare ahead for somebody.
对于任何更复杂的事情(实际上,对于这个用例也是如此),您可能希望考虑从任何确定的来源获取冻结替换,而不是通过从正则表达式模式中提取它。否则会有人面临代码维护的噩梦。