正则表达式 - 在第一个和第三个字符之间插入一个特殊字符 (~),并且仅当存在完全匹配时

Posted

技术标签:

【中文标题】正则表达式 - 在第一个和第三个字符之间插入一个特殊字符 (~),并且仅当存在完全匹配时【英文标题】:Reg Exp - insert a special character (~) between the first and the third character and only when an exact match is present 【发布时间】:2018-07-17 06:39:45 【问题描述】:

我的表有一列 MSG_INFO 包含示例数据:

Party is carrying gold in a car which is made of ,gold,
Party is carrying whitegold in a car which made of gold

我需要一个搜索 gold 的 SQL 表达式,如果存在完全匹配,那么我在完全匹配 gold 的第一个字符之后附加 ~ 并且当没有完全匹配时不执行任何操作.

gold 两边只能用空格或逗号包围。

预期输出:

Party is carrying g~old in a car which is made of ,g~old,
Party is carrying whitegold in a car which made of g~old

注意 - 在黄金前后插入~ 空格后仍应保留。

这是我开始的:

SELECT REGEXP_REPLACE (msg_info, '(^|\s|\W)(gold)($|\s|\W)', '\1~\2\3', 1,0,'i')
FROM   table;

Party is carrying ~gold in a car which is made of ,~gold,
Party is carrying whitegold in a car which made of ~gold

它正确识别了gold 的正确实例,但它将~ 放在单词之前而不是第一个字符之后。

【问题讨论】:

背景问题:***.com/questions/47973053/… 【参考方案1】:

(gold)拆分为两种模式:(g)(old)在搜索字符串中,例如:

select regexp_replace('Party is carrying gold in a car which is made of ,gold,',
        '(^|\s|\W)(g)(old)($|\s|\W)', '\1\2~\3\4', 1,0,'i') from dual
union all
select regexp_replace('Party is carrying whitegold in a car which made of gold',
        '(^|\s|\W)(g)(old)($|\s|\W)', '\1\2~\3\4', 1,0,'i') from dual;


Party is carrying g~old in a car which is made of ,g~old,
Party is carrying whitegold in a car which made of g~old

【讨论】:

sqlfiddle.com/#!4/0160d/1 - 你能检查一下这个例子吗,我试着修改你的查询。它没有按我的预期工作。有什么我想念的吗。 算了,我知道错在哪里。引号放错地方了。将通过另一轮测试来确认。 我们为什么要引入两个模式而不是一个要搜索的单词,只是为了插入〜我们正在拆分它。 @user3442679 :如果你不需要匹配大小写,只是想用g~old替换gold,那么不需要拆分,我们可以简单地使用'\1g~old\3'作为替换模式。【参考方案2】:

试试这个,应该可以的。

REGEX_REPLACE(msg_info,'([\s,](g)(o)(l)(d)[\s,])','\2

【讨论】:

【参考方案3】:

这个正则表达式有点不同,它使用嵌套组。不要忘记行首的“Gold”。

SQL> with tbl(msg_info) as (
      select 'Party is carrying gold in a car which is made of ,gold,' from dual union all
      select 'Party is carrying whitegold in a car which made of gold' from dual union all
      select 'Gold Party gold is carrying whitegold gold goldstar gold' from dual
    )
    select regexp_replace(msg_info, '(( |,|^)g)(old( |,|$))', '\1~\3', 1, 0, 'i') after
    from tbl;

AFTER
--------------------------------------------------------------------------------

Party is carrying g~old in a car which is made of ,g~old,
Party is carrying whitegold in a car which made of g~old
G~old Party g~old is carrying whitegold g~old goldstar g~old

SQL>

【讨论】:

以上是关于正则表达式 - 在第一个和第三个字符之间插入一个特殊字符 (~),并且仅当存在完全匹配时的主要内容,如果未能解决你的问题,请参考以下文章

SQL Regex 在第二个和第三个正斜杠之间选择字符串

正则表达式:匹配模式后跟一个空格但不匹配2个或更多空格或EOF

php正则表达式获取两个字符之间的文字

如何使用CHARINDEX和SUBSTRING在第二个和第三个“_”之间提取特定文本?

在第三个和第一个视图控制器之间传递数据

正则表达式获得两个字符串之间的内容