【问题标题】:Removing only one group with oracle regexp_replace使用 oracle regexp_replace 仅删除一组
【发布时间】:2019-02-01 10:44:30
【问题描述】:

我有一个字符串'hello big world',我想删除'big world',这样最终结果字符串就只是'hello'。我不知道会这么难。我得到的最接近的是:

declare
 l_string varchar2(40);
 begin
    l_string := 'hello big world,';
    dbms_output.put_line(l_string);
    l_string := regexp_replace(l_string, 'hello (.*),$', '\1');
    dbms_output.put_line(l_string); -- it returns 'big world' and that's the part I want to remove 
 end;
 /

【问题讨论】:

    标签: regex oracle regexp-replace


    【解决方案1】:

    它返回 big world,因为这就是您的代码所说的。 regexp_replace 函数中的最后一个参数是替换字符串。如果你想删除 big world 然后搜索它并使用一个空字符串作为你的替换,即

    regexp_replace(l_string, 'big world', '')
    

    【讨论】:

    • 哦,但我忘了提到有时它可能是“大地球”或“大太阳”。只有大更新这个词发生了变化。
    • 不管你搜索什么,为了移除搜索到的字符串,替换字符串必须是空字符串。
    • 如果字符串是“你好大世界,你好大地球,你好大太阳”怎么办?我可以在那种情况下使用 regexp_replace 吗?
    • 当然。您需要一个正则表达式来查找您想要删除的所有内容,但替换字符串仍然需要是空字符串。问题是你想从 hello big world, hello big earth, hello big sun 中删除什么?
    • '你好大世界,你好大地球,你好大太阳,'==>'你好,你好,你好,'
    【解决方案2】:

    你可以用这个:

    l_string := regexp_replace(l_string, 'hello [^,]*,', 'hello,');
    

    您的代码有 2 个问题:

    • 首先在pattern,你使用$,意味着oracle只在字符串末尾搜索匹配,所以对于字符串hello big world, hello big earth, hello big sun,oracle永远不会匹配hello big world,或@987654327部分@

    • 其次,在 replace_string 中,您使用反向引用 \1,同时在要删除的部分 - (.*) 中标记引用,而不是要保留的部分 - hello。如果你想使用反向引用,那么它应该是regexp_replace(l_string, '(hello) [^,]*,', '\1,');

    参考文档REGEXP_REPLACE

    【讨论】:

    • 您的代码将删除hello 之后的所有内容,, 除外。对于以下字符串,它将具有相同的结果。 regexp_replace('hello big test world,', 'hello [^,]*,', 'hello,')
    • @Deep 是的,我认为这就是 OP 想要的,正如他的其他评论 'hello big world, hello big earth, hello big sun,' ==> 'hello, hello, hello,'
    猜你喜欢
    • 2019-04-05
    • 2021-10-05
    • 2020-04-25
    • 1970-01-01
    • 2018-05-30
    • 1970-01-01
    • 2019-06-25
    • 2015-12-09
    • 1970-01-01
    相关资源
    最近更新 更多