有没有办法 select 某个字符之前的 n 个字符
Is there a way to select n characters that are before the a certain character
我有一个字符串,代表一个文件。
文件扩展名的大小不同。
'.' 之前的最后 2 个字符提供重要信息。
有没有办法(可能使用正则表达式)来更改这 2 个字符?
Mystring := blabla || two_characters_to_change || '.' || file_extension
Mystring_concrete_example := 'blabla93.pdf'
select regexp_replace('Mystring_concrete_example','??','39')
expected result:= 'blaba39.pdf'
有人知道我应该写什么而不是 '??',以便 select '.' 之前的 2 个字符?
我们可以使用INSTR
找到点,然后使用SUBSTRING
得到我们想要保留的部分。
create table paths(path varchar(100));
insert into paths select 'blabla93.pdf' from dual;
with findings as
(select
path,
INSTR( path, '.') pos
from paths)
select
substr(path,1,pos-3) || '22' || substr(path,pos) as newPath
from findings
| NEWPATH |
| :----------- |
| blabla22.pdf |
db<>fiddle here
如果您的扩展名不包含点(如 .tar.gz
),那么您可以搜索末尾的点并使用正则表达式组提取前两个字符:
with a as (
select 'blabla93.pdf' as file_
from dual
)
select
file_
, regexp_replace(
file_
, '(.*)(.{2})(\.[^.]+$)'
, '' || 'something' || ''
) as file_new
from a
FILE_ | FILE_NEW
:----------- | :------------------
blabla93.pdf | blablasomething.pdf
db<>fiddle here
解释:
(.*)
- 第一个捕获组,应包含任意数量 *
的任意字符 .
.
(.{2})
- 第二个捕获组,应该恰好包含两个 {2}
任意 .
个字符
(\.[^.]+$)
- 第 3 个捕获组,应以点 \.
开头,后跟任意字符的正数 +
,点 [^.]
除外,并放置在最前面字符串结尾 $
- 替换
\N
代表第 N
个捕获组。
您也可以使用这个包含解释的在线正则表达式测试器:https://regex101.com/。
我有一个字符串,代表一个文件。 文件扩展名的大小不同。 '.' 之前的最后 2 个字符提供重要信息。 有没有办法(可能使用正则表达式)来更改这 2 个字符?
Mystring := blabla || two_characters_to_change || '.' || file_extension
Mystring_concrete_example := 'blabla93.pdf'
select regexp_replace('Mystring_concrete_example','??','39')
expected result:= 'blaba39.pdf'
有人知道我应该写什么而不是 '??',以便 select '.' 之前的 2 个字符?
我们可以使用INSTR
找到点,然后使用SUBSTRING
得到我们想要保留的部分。
create table paths(path varchar(100));
insert into paths select 'blabla93.pdf' from dual;
with findings as
(select
path,
INSTR( path, '.') pos
from paths)
select
substr(path,1,pos-3) || '22' || substr(path,pos) as newPath
from findings
| NEWPATH | | :----------- | | blabla22.pdf |
db<>fiddle here
如果您的扩展名不包含点(如 .tar.gz
),那么您可以搜索末尾的点并使用正则表达式组提取前两个字符:
with a as ( select 'blabla93.pdf' as file_ from dual ) select file_ , regexp_replace( file_ , '(.*)(.{2})(\.[^.]+$)' , '' || 'something' || '' ) as file_new from a
FILE_ | FILE_NEW :----------- | :------------------ blabla93.pdf | blablasomething.pdf
db<>fiddle here
解释:
(.*)
- 第一个捕获组,应包含任意数量*
的任意字符.
.(.{2})
- 第二个捕获组,应该恰好包含两个{2}
任意.
个字符(\.[^.]+$)
- 第 3 个捕获组,应以点\.
开头,后跟任意字符的正数+
,点[^.]
除外,并放置在最前面字符串结尾$
- 替换
\N
代表第N
个捕获组。
您也可以使用这个包含解释的在线正则表达式测试器:https://regex101.com/。