简体   繁体   English

如何应用`REGEXP_SUBSTR`从字符串中提取特定的substring?

[英]How to apply `REGEXP_SUBSTR` to extract specific substring from string?

I have the following string 011/2020-PL00-70-31 (it could slightly different for example 011/2020-PL00-70-3 or 011/2020-PL00-70-310 ).我有以下字符串011/2020-PL00-70-31 (它可能略有不同,例如011/2020-PL00-70-3011/2020-PL00-70-310 )。 I need to extract from the string all string before last - .我需要从字符串中提取 last 之前的所有字符串- As a result of REGEXP_SUBSTR of 011/2020-PL00-70-310 I need to get 011/2020-PL00-70 only, ie without last 4 symbols (but in some case it could be without 2 or 3 symbols).由于REGEXP_SUBSTR011/2020-PL00-70-310 ,我只需要获取011/2020-PL00-70 ,即没有最后 4 个符号(但在某些情况下可能没有 2 或 3 个符号)。

I am new to regular expression in PL SQL, so sorry for question if it is so easy.我是 PL SQL 中正则表达式的新手,如果它这么简单,很抱歉。

Thanks a lot.非常感谢。

In this particular case I think you're overthinking your solution using regex.在这种特殊情况下,我认为您使用正则表达式过度考虑了您的解决方案。 You're hyphen is always the third hyphen so you can just use INSTR to find the third occurrence. You're hyphen 始终是第三个连字符,因此您可以使用INSTR查找第三个出现。 See this query here:在此处查看此查询:

SELECT SUBSTR(sample, 1, INSTR(sample, '-', 1, 3)-1) AS match
FROM sample_table;

I have linked my results with a SQLFiddle - http://sqlfiddle.com/#!4/c30207/7/0我已将我的结果与 SQLFiddle - http://sqlfiddle.com/#!4/c30207/7/0

You can use a regex capture group () to get only the part you need from a pattern.您可以使用正则表达式捕获组()从模式中仅获取您需要的部分。

SELECT REGEXP_SUBSTR(sample, '^(.*)-\d+$',1,1,'',1) AS sample2
FROM sample_table
SAMPLE2样品2
011/2020-PL00-70 011/2020-PL00-70
011/2020-PL00-70 011/2020-PL00-70
011/202-PL00-70 011/202-PL00-70

Demo on db<>fiddle here关于db<>fiddle 的演示在这里

Test of the regex pattern here在此处测试正则表达式模式

You might just replace the trailing digits away:您可能只是将尾随数字替换掉:

REGEXP_REPLACE(whatever, '(-[^-]+)$', '')

The regex catches a minus sign and any subsequent non-minus characters ( [^-]+ ; alternatively you can match against digits only: \d+ ) – if they are located at the end of the string ( $ ), so intermediate digits are protected.正则表达式捕获一个减号和任何后续的非减号字符( [^-]+ ;或者,您可以仅匹配数字: \d+ ) -如果它们位于字符串的末尾( $ ),所以中间数字是受保护。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM