2

I know this topic was discussed multiple times, I looked at multiple posts and answers, but could not find exactly what I need to do.

I am trying to search the string, that has multiple values of varchar2 separated by ':', and if the match is found on another string, delete part of the string that matched, and update the table with the rest of the string.

I wrote the code using combination of str and instr functions, but looking for more elegant solution using regexp, or collections.

For example, the input string looks like this: ('abc:defg:klmnp). Need to find for example the piece of the string (could be at any position), and remove it, that result would look like this: (abc:klmnp)?

EDIT - copied from comment: The input string (abc:defg:klmn:defgb). Let's say I am looking for defg, and only defg will have to be removed, not defgb. Now, like I mentioned before, next time around, I might be looking for the value in position 1, or the last position. So the desired part of the string to be removed might not always be wrapped in ':' from the both sides, but depending where it is in the string, either from the right, or from the left, or from both sides.

4

2 回答 2

1

您可以结合使用 LIKE、REPLACE 和 TRIM 函数来完成此操作。

select trim(':' from 
            replace(':'||your_column||':',':'||search_string||':',':')
           ) from table_name
 where ':'||your_column||':' like '%:'||search_string||':%';

想法是,

  • 用冒号包围列并使用 LIKE 函数查找匹配项。
  • 在此类匹配的行上,使用 REPLACE 将搜索字符串与周围的冒号一起替换为单个冒号。
  • 然后使用 TRIM 删除周围的冒号。

sqlfiddle演示

于 2013-07-26T11:48:07.690 回答
0

编辑(简化)也许这就是你需要的:

SELECT REGEXP_REPLACE(REPLACE('abc:defg:klmnop', ':defg:', ':'), '(^defg:|:defg$)', '')
     , REGEXP_REPLACE(REPLACE('defg:klmnop:abc', ':defg:', ':'), '(^defg:|:defg$)', '')
     , REGEXP_REPLACE(REPLACE('abc:klmnop:defg', ':defg:', ':'), '(^defg:|:defg$)', '')
     , REGEXP_REPLACE(REPLACE('abc:klmnop:defgb:defg', ':defg:', ':'), '(^defg:|:defg$)', '')
  FROM DUAL
;

从 start、middle 和 end 中删除 defg,并忽略 defgb,给出:

  • abc:klmnop
  • klmnop:abc
  • abc:klmnop
  • abc:klmnop:defgb

要更新表格,您可以:

UPDATE my_table
   SET value = REGEXP_REPLACE(REGEXP_REPLACE(value, ':defg:', ':'), '(^defg:|:defg$)', '')
--  WHERE REGEXP_LIKE(value, '(^|.*:)defg(:.*|$)')
  WHERE value LIKE '%defg%'
;

(尽管可能需要调整 where 的最终正则表达式以匹配,但很难测试......)

于 2013-07-26T11:30:31.673 回答