简体   繁体   中英

I need oracle regex to replace 2nd to 4th position characters to symbol

I have number like 94335251812 and I want to replace number at 2nd to 4th position to symbol.

For example

94335251812 -> 9___5251812
123456789 -> 1___56789

You want second to fourth character to be replaced to underbar( _ ).

Dot( . ) means any character. It means you can map any value with dot. It's like full outer join in database concept. You can join any character.

For example, following will replace first 3 character to 'xxx'.

select regexp_replace('1@#45', '...', 'xxx') from dual; -- 'xxx45'

You can repeat with quantifier as {number} .

select regexp_replace('1@#45', '.{3}', 'xxx') from dual; -- 'xxx45'

But you need to find 2th to 4th character only. So you can use 4th argument which is starting index.

select regexp_replace('1@#45', '.{3}', 'xxx', 2) from dual; -- '1xxx5'

This is simple, but not easy to me because all editor I use does not support starting index for replacement. (Notepad++, VSCode, Visual Studio...)

So I find all character by repeating dot( . ).

-- .: 1st characther
-- .{3}: 2nd to 4th characters
-- .+: all characters to end of string
select regexp_replace('1@#45', '..{3}.+', 'xxx') from dual; -- 'xxx'

Result is wrong because I replaced whole string, so I need to restore original value.

You can tag your search using group as (pattern1)(pattern2) to reference in replace. You can reference group by index as \1\2 .

Following has same result because all group was restored.

select regexp_replace('1@#45', '(.)(.{3})(.+)', '\1\2\3') from dual; -- 1@#45

Now you mapped all characters with dot( . ) and divided what to restore and what to replace with group. You only need second group to be replaced with 3 _ .

select regexp_replace('1@#45', '(.)(.{3})(.+)', '\1___\3') from dual; -- 1___5

https://dbfiddle.uk/?rdbms=oracle_11.2&fiddle=de84fbd3ff667a010b03958c52b849c6

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM