查找子串直到最后一次出现

Find substring till last occurrence

我想获取如下字符串的子字符串:filename_ip_time.pdf 我想要 select filename_ip,这是直到最后一次出现 '_'

的字符串

使用-1作为INSTR的起始位置,从字符串末尾开始搜索:

select INSTR('filename_ip_time.pdf', '_', -1) from dual

所以如果你想 select filename_ip,你应该这样做:

SELECT   SUBSTR ('filename_ip_time.pdf',
                 0,
                 (INSTR ('filename_ip_time.pdf', '_', -1)) - 1)
  FROM   DUAL

你可以简单地使用 SUBSTRINSTR.

例如,

Here INSTR will give the first position of _ from the end.

SQL> WITH DATA AS(
  2  SELECT 'filename_ip_time.pdf' str FROM dual
  3  )
  4  SELECT SUBSTR(str, 1, instr(str, '_', -1, 1) -1) FROM DATA
  5  /

SUBSTR(STR,
-----------
filename_ip

SQL>

或者,

If you know that you need substr till the second occurrence of _, then use INSTR to get the position of second occurrence of _ from the start.

例如,

 SQL> WITH DATA AS(
  2  SELECT 'filename_ip_time.pdf' str FROM dual
  3  )
  4  SELECT SUBSTR(str, 1, instr(str, '_', 1, 2) -1) FROM DATA
  5  /

SUBSTR(STR,
-----------
filename_ip

SQL>

另一种使用 REGEXP_REPLACE() 的方法:

SQL> select regexp_replace('filename_ip_time.pdf', '^(.*)_.*$', '') from dual;

REGEXP_REPL
-----------
filename_ip

SQL>

其中正则表达式可以读作: Return 模式匹配的第一个记住组 (\1):

^  Start of the line
(  start the first group to remember
.  any character
*  any number of the previous character (any character)
)  end the first group, followed by
_  A literal underscore
.*  followed by any number of any characters 
$  until the end of the line.

所以本质上,您返回的是字符串的第一部分,但不包括最后一个下划线,然后是该行的其余部分。对我来说,它比嵌套的 substr() 和 instr() 更清晰,但您需要了解正则表达式,当您需要进行更复杂的模式匹配时,这最终会给您更多的力量。