1

我有一个字符串 'MCDONALD_YYYYMMDD.TXT' 我需要使用正则表达式并在给定字符串中的字母 'D' 之后附加 '**'。(即在第 9 位的字符串中,如果 star_len = 2 o/p = ''MCDONALD??_YYYYMMDD.TXT' 如果 star_len = 1 o/,我需要基于列值 'star_len' 附加 '*' p = ''MCDONALD?_YYYYMMDD.TXT'

4

3 回答 3

1
with
     inputs ( filename, position, symbol, len ) as ( 
       select 'MCDONALD_20170812.TXT', 9, '*', 2 from dual
     )
-- End of simulated inputs (for testing purposes only, not part of the solution).
-- SQL query begins BELOW THIS LINE.
select substr(filename, 1, position - 1) || rpad(symbol, len, symbol) 
                                         || substr(filename, position) as new_str
from   inputs
;

NEW_STR
-----------------------
MCDONALD**_20170812.TXT
于 2017-08-01T19:49:13.423 回答
0
select regexp_replace('MCDONALD_YYYYMMDD.TXT','MCDONALD','MCDONALD' || 
          decode(star_len,1,'*',2,'**'))
from dual

这就是你可以做到的方式。我认为你不需要它作为正则表达式,但如果它总是“MCDONALD”的话。

编辑:如果您还需要在字符串中提供位置,我认为常规的旧子字符串应该可以工作。

select substr('MCDONALD_YYYYMMDD.TXT',1,position-1) || 
          decode(star_len,1,'*',2,'**') || substr('MCDONALD_YYYYMMDD.TXT',position) 
from dual

其中 position 和 star_len 都是您提供的某个表中的列(而不是双列)。

EDIT2:为了更清楚起见,这是另一个使用 with 子句的示例,因此它在不添加表的情况下运行。

    with testing as
(select 'MCDONALD_YYYYMMDD.TXT' filename,
        9 positionnum,
        2 star_len
from dual)

select substr(filename,1,positionnum-1) || 
            decode(star_len,1,'*',2,'**') || 
            substr(filename,positionnum)
from testing
于 2017-08-01T19:15:26.507 回答
0

For the fun of it, here's a regex_replace solution. I went with a star since that what your variable was called even though your example used a question mark. The regex captures the filename string in 2 parts, the first being from the start up to 1 character before the position value, the second the rest of the string. The replace puts the captured parts back together with the stars in between.

with tbl(filename, position, star_len ) as ( 
       select 'MCDONALD_20170812.TXT', 9, 2 from dual
)
select regexp_replace(filename, 
       '^(.{'||(position-1)||'})(.*)$', '\1'||rpad('*', star_len, '*')||'\2') as fixed
from tbl;
于 2017-08-01T20:56:05.850 回答