gpt4 book ai didi

regex - 将字段中的未转义文本添加到 postgres 中的正则表达式的正确方法?

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

将文本文本值从字段添加到 postgres 中的正则表达式的正确方法是什么?

例如,如果不进行转义,some_field 可能包含无效的正则表达式语法:

where some_text ~* ('\m' || some_field || '\M');

最佳答案

最简单的方法是使用正则表达式来准备要在正则表达式中使用的字符串。转义字符串中的非单词字符应该足以使其成为正则表达式安全的,例如:

=> select regexp_replace('. word * and µ{', E'([^\\w\\s])', E'\\\\\\1', 'g');
regexp_replace
--------------------
\. word \* and µ\{

所以像这样的东西应该可以正常工作:

where some_text ~* x || regexp_replace(some_field, E'([^\\w\\s])', E'\\\\\\1', 'g') || y

其中 xy 是正则表达式的其他部分。

如果最后不需要正则表达式(即上面没有 y),那么您可以使用 (?q) :

An ARE can begin with embedded options: a sequence (?xyz) (where xyz is one or more alphabetic characters) specifies options affecting the rest of the RE.

q 表示:

rest of RE is a literal ("quoted") string, all ordinary characters

所以你可以使用:

where some_text ~* x || '(?q)' || some_field

在这种有限的情况下。

关于regex - 将字段中的未转义文本添加到 postgres 中的正则表达式的正确方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11111304/

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