Oracle regexp - 从字符串中删除尾随下划线和数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7333606/
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
Oracle regexp - removing trailing underscore and numbers from string
提问by DavidP
I have values like this: aaa_1, bb_5, c_21, a_b. Now i need remove trailing underscore and numbers from this values. A_b (string_string) is valid value and need not to be removed. Basicaly, i need regexp patern to extract only trailing _[any number of digits] from string.
我有这样的值:aaa_1、bb_5、c_21、a_b。现在我需要从这个值中删除尾随下划线和数字。A_b (string_string) 是有效值,不需要删除。基本上,我需要正则表达式模式从字符串中仅提取尾随 _[任意数量的数字]。
I am using Oracle 11gR2
我正在使用 Oracle 11gR2
Any suggestion?
有什么建议吗?
回答by Ollie
You need to use REGEXP_REPLACE with the regex expression '\_[[:digit:]]{1,}'
您需要将 REGEXP_REPLACE 与正则表达式 '\_[[:digit:]]{1,}' 一起使用
This translates to find the (escaped) underscore with one or more digits after it:
这意味着找到后面有一个或多个数字的(转义的)下划线:
e.g.
例如
SELECT REGEXP_REPLACE('a_b', '\_[[:digit:]]{1,}'),
REGEXP_REPLACE('aaa_1', '\_[[:digit:]]{1,}'),
REGEXP_REPLACE('c_21', '\_[[:digit:]]{1,}'),
REGEXP_REPLACE('bb_5', '\_[[:digit:]]{1,}')
FROM dual;
Returns
退货
a_b
aaa
c
bb
If you want to make sure you only remove the underscore and digits when there are no alpha characters then add the $ to the end of the regex string to signify the end of the string.
如果您想确保仅在没有字母字符时删除下划线和数字,则将 $ 添加到正则表达式字符串的末尾以表示字符串的结尾。
e.g. First with the "$" second without
例如,第一个带有“$”,第二个没有
SELECT REGEXP_REPLACE('bb_5b', '\_[[:digit:]]{1,}$'),
REGEXP_REPLACE('bb_5b', '\_[[:digit:]]{1,}'),
REGEXP_REPLACE('bb_55', '\_[[:digit:]]{1,}$'),
REGEXP_REPLACE('bb_55', '\_[[:digit:]]{1,}')
FROM dual;
Returns
退货
bb_5b
bbb
bb
bb
Regular expressions can be awkward but this link is one of the easiest to understand that I have found for Oracle regex expressions: http://www.dba-oracle.com/t_regular_expressions.htm
正则表达式可能很笨拙,但此链接是我为 Oracle 正则表达式找到的最容易理解的链接之一:http: //www.dba-oracle.com/t_regular_expressions.htm
Hope this helps.
希望这可以帮助。
回答by furman87
Here is another version, which will ignore any values that start with numbers if you have them. Same basic approach as Ollie, but takes into account the first part of the value to make sure they are letters. It captures both parts of the value and replaces it with the first part if it matches your criteria.
这是另一个版本,如果您有数字,它将忽略任何以数字开头的值。与 Ollie 相同的基本方法,但考虑到值的第一部分以确保它们是字母。它捕获值的两个部分,如果它符合您的条件,则将其替换为第一部分。
select
regexp_replace('A_1', '([A-Za-z]+)(\_\d+)', ''),
regexp_replace('A_B', '([A-Za-z]+)(\_\d+)', ''),
regexp_replace('cc_21', '([A-Za-z]+)(\_\d+)', ''),
regexp_replace('1_1', '([A-Za-z]+)(\_\d+)', '')
from dual;