How can I replace multiple words “globally” using regexp_replace in Oracle?

一曲冷凌霜 提交于 2021-02-10 16:02:30

问题


I need to replace multiple words such as (dog|cat|bird) with nothing in a string where there may be multiple consecutive occurrences of a word. The actual code is to remove salutations and suffixes from a name. Unfortunately the garbage data I get sometimes contains "SNERD JR JR."

I was able to create a regular expression pattern that accomplishes my goal but only for the first occurrence. I implemented a stupid hack to get rid of the second occurrence, but I believe there has to be a better way. I just can't figure it out.

Here is my "hacked" code;

  FUNCTION REMOVE_SALUTATIONS(IN_STRING VARCHAR2) RETURN VARCHAR2 DETERMINISTIC
  AS
    REGEX_SALUTATIONS VARCHAR2(4000) := '(^|\s)(MR|MS|MISS|MRS|DR|MD|M D|SR|SIR|PHD|P H D|II|III|IV|JR)(\.?)(\s|$)';
  BEGIN
    RETURN TRIM(REGEXP_REPLACE(REGEXP_REPLACE(IN_STRING,REGEX_SALUTATIONS,' '),REGEX_SALUTATIONS,''));
  END REMOVE_SALUTATIONS;

I was actually proud that I was able to get this far, as regular expression are not very regular to me. All help is appreciated.

EDIT:

The default for regexp_replace based on my understanding is to do a global replace. But on the outside chance my DB is configured different I did try;

select REGEXP_REPLACE('SNERD JR JR','(^|\s)(MR|MS|MISS|MRS|DR|MD|M D|SR|SIR|PHD|P H D|II|III|IV|JR)(\.?)(\s|$)',' ',1,0) from dual;

and the results are;

SNERD JR

回答1:


Use occurrence parameter of REGEXP_REPLACE function. The docs says:

occurrence is a nonnegative integer indicating the occurrence of the replace operation:

  • If you specify 0, then Oracle replaces all occurrences of the match.
  • If you specify a positive integer n, then Oracle replaces the nth occurrenc

https://docs.oracle.com/cd/B28359_01/server.111/b28286/functions137.htm#SQLRF06302

It should look like:

...
REGEXP_REPLACE(IN_STRING,REGEX_SALUTATIONS,' ', 1,0 )
...


来源:https://stackoverflow.com/questions/48989666/how-can-i-replace-multiple-words-globally-using-regexp-replace-in-oracle

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!