【问题标题】:How to not replace the word with in a pattern using regexp_replace?如何不使用 regexp_replace 替换模式中的单词?
【发布时间】:2020-02-01 00:46:26
【问题描述】:

在下面的文字中,单词编号出现了两次。我不想替换出现在模式<a hef and a> 之间的单词。有没有办法只使用 regexp_replace 来避免这种模式之间的单词?

代码没有按预期工作。

with t as (
select 'The Number can be a whole number. <a href https://number.com a>' as text from dual)
select regexp_replace(text,'^[<a href].*number.*[a>]','num') from t

预期的结果是

The num can be a whole num. <a href https://number.com a>

【问题讨论】:

  • 除了 Regex 之外的其他解决方案是使用 SUBSTR 和 INSTR 在 的基础上拆分字符串。然后只需使用 REPLACE 函数而不是正则表达式。更简单的解决方案,但如果有多个 HTML 标签,这将很难。我们可以为相同的(?&lt;!\/|\.)number 创建正则表达式,但 Oracle 不会接受这种正则表达式。您可以在 Regex 101 中使用此 Regex,它可以工作,但不能在 Oracle 中工作。示例:regex101.com/r/Bb54Pr/1
  • 你不能通过一次调用 regexp_replace 来做到这一点,因为你想用一个新的字符串替换匹配项并保留不匹配项(括号内的匹配项)。只有将回调函数作为替换参数传递给正则表达式替换函数或使用前瞻才能实现。
  • 这里是我上面提到的方式的例子。同样,只有当 HTML 标记出现一次时它才会有帮助,否则它会惨遭失败。 (不是动态的)with t as ( select 'The number can be a whole number. &lt;a href https://number.com a&gt;' as text from dual) select regexp_replace(SUBSTR(text,1,INSTR(text,'&lt;',1)-1),'(number)','num') || SUBSTR(text, INSTR(text,'&lt;',1)) from t
  • html 标签可以在文本中的任何位置。仅当 HTML 标记位于文本之后时,上面的代码才有效。对吗?

标签: sql regex oracle regexp-replace


【解决方案1】:

我不知道如何在一次调用中完成,但您可以通过多次调用来完成。

  • 第一次调用:将href 中出现的“数字”转换为不同的字符串
  • 第二次调用:转换剩余的“数字”出现
  • 第三次调用:将出现的“不同字符串”转换回“数字”。

例如,

with t as (
select 'The Number can be a whole number. <a href https://number.com a>' as text from dual)
select regexp_replace(
          regexp_replace(
            regexp_replace(text,'(<a href.*)(number)(.*a>)','\1$$$SAVE_NBR$$$\3'),
              'number', 'num'),
            '\$\$\$SAVE_NBR\$\$\$','number')
from t

我不知道为什么我在“不同的字符串”中使用了“$”……它只会让它变得更难。关键是选择一个永远不会在您的输入中自然出现的字符串。

【讨论】:

    【解决方案2】:

    这将起作用:

    with t as (
    select 'The Number can be a whole number. <a href https://number.com a>' as text from dual)
    select regexp_replace(regexp_replace(text,' Number',' num'),' number',' num') from t
    

    【讨论】:

    • 如果在&lt;a hrefa&gt; 之间有另一个" number" 并带有前导空格,例如......... &lt;a href number https://number.com a&gt; 怎么办?
    猜你喜欢
    • 2018-08-05
    • 2021-11-01
    • 2023-04-07
    • 1970-01-01
    • 2020-01-28
    • 1970-01-01
    • 2021-10-05
    • 2022-12-18
    • 2019-06-09
    相关资源
    最近更新 更多