db2 remove all non-alphanumeric, including non-printable, and special characters

生来就可爱ヽ(ⅴ<●) 提交于 2020-12-15 07:18:56

问题


This may sound like a duplicate, but existing solutions does not work. I need to remove all non-alphanumerics from a varchar field. I'm using the following but it doesn't work in all cases (it works with diamond questionmark characters):

  select TRANSLATE(FIELDNAME, '?',
                 TRANSLATE(FIELDNAME , '', 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789')) 
   from TABLENAME

What it's doing is the inner translate parse all non-alphanumeric characters, then the outer translate replace them all with a '?'. This seems to work for replacement character�. However, it throws The second, third or fourth argument of the TRANSLATE scalar function is incorrect. which is expected according to IBM:

The TRANSLATE scalar function does not allow replacement of a character by another character which is encoded using a different number of bytes. The second and third arguments of the TRANSLATE scalar function must end with correctly formed characters.

Is there anyway to get around this?

Edit: @Paul Vernon's solution seems to be working:

· 6005308      ??6005308
–6009908       ?6009908
–6011177       ?6011177
��6011183�� ??6011183??

回答1:


Try regexp_replace(c,'[^\w\d]','') or regexp_replace(c,'[^a-zA-Z\d]','')

E.g.

select regexp_replace(c,'[^a-zA-Z\d]','') from table(values('AB_- C$£abc�$123£')) t(c)

which returns

1
---------
ABCabc123

BTW Note that the allowed regular expression patterns are listed on this page Regular expression control characters

Outside of a set, the following must be preceded with a backslash to be treated as a literal

* ? + [ ( ) { } ^ $ | \ . /

Inside a set, the follow must be preceded with a backslash to be treated as a literal

Characters that must be quoted to be treated as literals are [ ] \ Characters that might need to be quoted, depending on the context are - &



来源:https://stackoverflow.com/questions/54697743/db2-remove-all-non-alphanumeric-including-non-printable-and-special-characters

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