gpt4 book ai didi

regex - 带下划线的特殊字符(postgres 中的正则表达式)

转载 作者:行者123 更新时间:2023-11-29 11:56:07 25 4
gpt4 key购买 nike

如何在 Postgres 中识别包含下划线的正则表达式模式?

这是我实际的正则表达式:

[^\w]+

它匹配字符很好,问题是下划线。例如,当我使用该正则表达式调用函数时:

select regexp_replace('hello_world!', '[^\w]+', ' ', 'g')

我期待着 hello world。如何匹配下划线?

最佳答案

问题是 \w 也匹配下划线,当您在否定字符类中使用它时,模式与 _ 字符不匹配。您可以查看 class-shorthand escape table :

\w   [[:alnum:]_] (note underscore is included)

要删除除字母数字以外的所有字符,您可以取出 _ 并使用

select regexp_replace('hello_world!', '[^[:alnum:]]+', ' ', 'g')

这里,[^[:alnum:]]+ 匹配一个或多个 (+) 个连续的字符,除了 ([^...] 是一个否定的括号表达式)字母和数字([:alnum:] POSIX 字符类匹配字母和数字)。

enter image description here

嗯,你也可以使用 (?:\W|_)+。不幸的是,像 [\W_]+ 这样的常见正则表达式结构将不起作用,因为 \W (以及其他否定的简写形式,如 \S\D 是非法的括号内表达式。更多详细信息可在 manual 中找到:

Within bracket expressions, \d, \s, and \w lose their outer brackets, and \D, \S, and \W are illegal. (So, for example, [a-c\d] is equivalent to [a-c[:digit:]]. Also, [a-c\D], which is equivalent to [a-c^[:digit:]], is illegal.)

要去除尾随/前导空格,您可以使用 trim:

select trim(regexp_replace('hello_world!', '[^[:alnum:]]+', ' ', 'g'))

关于regex - 带下划线的特殊字符(postgres 中的正则表达式),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55301882/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com