如何用oracle中的's'替换字符串中第一个出现的字符'e'?

时间:2013-06-08 18:55:05

标签: sql oracle

就像我的table-column first_name由值

组成

如first_name:

leena,
stev,
neene,
ajay,
vine.

我的问题是我只想用's'替换第一次出现的'e'字符,而'e'的另一次出现必须保持与's'不能替换的相同。我需要输出如下。

lsena,
stsv,
nsene,
ajay,
vins.

3 个答案:

答案 0 :(得分:17)

试试这个:

select regexp_replace(first_name,'e','s',1,1) 
from your_table

这里解释了regexp_replace函数: http://www.java2s.com/Book/Oracle/String_Functions/REGEXP_REPLACE_function.htm

答案 1 :(得分:0)

另一种变体,不像regexp_replace那么优雅,但也有效:

with example_data as (
  select 'leena' field0 from dual union all
  select 'stev'  field0 from dual union all
  select 'neene' field0 from dual union all
  select 'ajay'  field0 from dual union all
  select 'vine'  field0 from dual 
)
select
  field0,
  decode( instr(field0,'e'),
          0, field0, 
          substr(field0,1,instr(field0,'e')-1) || 's' || substr(field0,instr(field0,'e')+1)) 
from 
  example_data

SQLFiddle

仅供参考。

答案 2 :(得分:0)

Mostly we can use 'regexp_replace' to replace particular character from a particular occurrence.

最简单的解决方案之一:

  SELECT REPLACE(
                 SUBSTR(COLUMN_NAME, 1,
                        instr(COLUMN_NAME,'e',1)),
                 'e', 's')
         || SUBSTR(COLUMN_NAME,
                   INSTR(COLUMN_NAME,'e',1)+1,
                   LENGTH(COLUMN_NAME))
  FROM TABLE_NAME