6

like in my table-column first_name consists of values

first_name:

leena,
stev,
neene,
ajay,
vine.

and my question is that i only want to replace the first occurrence of character 'e' with 's' and the other occurrence of 'e' must remains the same that is it would not be replaced by 's'. And i need the output like below.

lsena,
stsv,
nsene,
ajay,
vins.

3 Answers 3

23

Try this:

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

The regexp_replace function is explained here: http://www.java2s.com/Book/Oracle/String_Functions/REGEXP_REPLACE_function.htm

3
  • You are correct, but I am unable to upvote you as you've completely failed to explain why and how this answers the question.
    – Ben
    Jun 8, 2013 at 19:14
  • 2
    Added a link to the documentation. Did not know that I needed to explain why this works and not sure what to answer to how it works. This is the SQL the OP was looking for, he can lookup the details of the function. Jun 8, 2013 at 19:20
  • The documentation is here: docs.oracle.com/cd/E11882_01/server.112/e26088/functions149.htm, it works because of the fifth parameter, which is the occurrence of the matched string that needs to be replaced. As this is greater than 0 regexp_replace() replaces the nth, in this case first, occurrence of the pattern 'e'. The fourth parameter is required when the fifth is used, 1 is the default and is the start position where the search should begin.
    – Ben
    Jun 8, 2013 at 19:29
0

Another variant, not so elegant as regexp_replace, but works too:

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

Just for illustration.

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

One of the simplest solution :

  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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.