【问题标题】:How to replace only certain part of the text in Oracle?如何仅替换 Oracle 中文本的某些部分?
【发布时间】:2020-01-27 09:43:33
【问题描述】:

我正在尝试替换文本中的某些单词。但是,如果它是 url 的一部分,则不希望该词被替换。例如:技术一词。它在两个地方都被替换了(包括 url)。

select regexp_replace('Part of the Technical Network Group https://technical.com/sites/',
                      'technical','tech',1,0,'i')
  from dual

输出:

Part of the tech Network Group https://tech.com/sites/

预期输出:

Part of the tech Network Group https://technical.com/sites/

【问题讨论】:

    标签: sql oracle replace string-matching regexp-replace


    【解决方案1】:

    此方法使用一个 regexp_replace() 调用。仅当它前面是行首或空格时,它才匹配单词“技术”(不区分大小写),并保存前面的字符。它被保存的字符(由'\1' 引用)替换,后跟“tech”。

    with tbl(str) as (
      select 'Technical Part of the Technical Network Group https://technical.com/sites/' from dual
    )
    select regexp_replace(str, '(^| )technical', '\1tech', 1, 0, 'i') fixed
    from tbl;
    
    FIXED                                                           
    ----------------------------------------------------------------
    tech Part of the tech Network Group https://technical.com/sites/
    

    【讨论】:

      【解决方案2】:

      分两步完成。

      首先,如果单词出现在单词之间,其次如果单词是句子的第一个单词。

      select 
            regexp_replace(regexp_replace('technical Part of Technical Group https://technical.com/sites/',
                           ' technical', 
                           ' tech',1,0,'i'), 'technical ', 'tech ',1,0,'i') 
        from dual
      

      希望这能解决您的问题。

      【讨论】:

      • 如果我们在文本的开头有单词呢?它不会取代它,因为它前面没有空格。
      • 这是你的答案。我暂时把这个词改成了***,然后又变回原来的样子。请参阅上面的答案。
      • 上面的查询给出Part of tech Group https:technical.com/sites/作为结果(i.e..https后没有斜杠
      • 这是一个陷阱。感谢您指出@BarbarosÖzhan。我已经更新了答案。
      • @BarbarosÖzhan 我们需要 2. 如果技术是字符串的第一个单词怎么办?见link
      猜你喜欢
      • 2017-08-30
      • 2021-01-14
      • 2017-08-30
      • 2011-12-31
      • 2023-01-03
      • 2021-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多