【问题标题】:Replace all characters except ascii 32 to 127 and ascii 0, 13, 27 in postgres sql将postgres sql中除ascii 32以外的所有字符替换为127和ascii 0、13、27
【发布时间】:2015-09-06 20:17:34
【问题描述】:

postgres sql中除了ascii 32到127和ascii 0、13、27之外,有什么函数可以替换所有字符。我不想替换空格、换行符等。我想替换奇怪的字符,如俱乐部标志、正方形或奇怪的星号。

我尝试像下面这样修改 regexp_replace,但它不起作用。

select regexp_replace('abc$wanto&tore9046move#special~04 chars', '[^\x00-\x7f]', '', 'g') 
--This is giving error ERROR: 22021: invalid byte sequence for encoding "UTF8": 0x00

select *, regexp_replace('abc$wanto&tore9046move#special~04 chars', '[^[:ascii:]]', '', 'g')
--This one is taking everything beyond 255 also in the set. 

非常感谢您的时间和帮助

【问题讨论】:

    标签: sql regex postgresql greenplum


    【解决方案1】:

    尝试 unicode 范围:

    select regexp_replace('abc$wanto&tore9046move#special~04 chars', '[\u0080-\u00ff]', '', 'g')
    

    Reference

    这将删除128-255 ascii 范围内的任何字符。

    【讨论】:

    • 方形和星号在1-127 范围内,因此不会使用上面的方法替换。
    • 对不起。我不知道。谢谢你。我纠正了我的问题。 :)。
    【解决方案2】:

    你几乎是对的:

    select regexp_replace('abc$wanto&tore9046move#special~04 chars', '[^\x00-\x7f]', '', 'g') 
    

    但空字节 \x00 在 PostgreSQL 字符串文字中无效,因此您必须从 \x01 开始。您想要的范围从 32 (0x20) 开始,所以使用它加上一些特定的包含 13 (0x0d) 和 27 (0x1b):

    select regexp_replace('abc$wanto&tore9046move#special~04 chars', '[^\x20-\x7f\x0d\x1b]', '', 'g')
    

    或者,使用更有用的输入:

    regress=> select regexp_replace('aáiï*∞ıb ', '[^\x20-\x7f\x0d\x1b]', '', 'g');
     regexp_replace 
    ----------------
     ai*b 
    (1 row)
    

    【讨论】:

    • 最后一个正则表达式是唯一真正完成可能需要的工作的正则表达式,因为其他正则表达式假设在较低范围内没有不可打印的字符,这是不准确的。
    猜你喜欢
    • 1970-01-01
    • 2015-06-25
    • 1970-01-01
    • 2020-07-12
    • 2023-03-12
    • 2021-12-31
    • 1970-01-01
    • 2011-02-01
    • 2012-04-02
    相关资源
    最近更新 更多