【问题标题】:regexp_replace in postgres keep only desired with single spacepostgres 中的 regexp_replace 只保留需要的单个空格
【发布时间】:2017-08-03 11:55:17
【问题描述】:

我想要的是像这样转一个字符串;

10 - 15 st. pan,cras

10 - 15 ST PANCRAS

我得到了大部分的方式

 `select upper(regexp_replace('10  -  15 st.  pan,cras', '[^a-zA-Z 0-9-]', '', 'g'));`

但我似乎无法删除数字周围的双空格。我试过了,在表达式中加了一个额外的空格;

 `select upper(regexp_replace('10  -  15 st.  pan,cras', '[^a-zA-Z  0-9-]', '', 'g'));`

但结果没有区别。我正在使用regexp_replace,因为我发现substring 语法更难遵循。 9.6 上的字符串存储在text

【问题讨论】:

    标签: sql regex postgresql postgres-9.6


    【解决方案1】:

    你可以只为一个表达式添加空间折叠,像这样:

    t=# select regexp_replace('q            q','( ){1,}',' ','g');
     regexp_replace
    ----------------
     q q
    (1 row)
    

    如果连续找到一个或多个后续空格,则替换为单个空格。

    所以在你的情况下

    t=# select regexp_replace(upper(regexp_replace('10  -  15 st.  pan,cras', '[^a-zA-Z 0-9-]', '', 'g')),'( ){1,}',' ','g');
       regexp_replace
    --------------------
     10 - 15 ST PANCRAS
    (1 row)
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-10
    • 1970-01-01
    • 2014-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多