代码之家  ›  专栏  ›  技术社区  ›  vick_4444

Oracle sql REGEXP\u REPLACE expression替换与模式匹配的字符串中的数字

  •  1
  • vick_4444  · 技术社区  · 7 年前

    我有一个字符串“ABC”。1.2.3' 我想用1代替中间的数字。

    Input 'ABC.1.2.3'
    Output 'ABC.1.1.3'
    
    Input 'XYZ.2.2.1'
    Output 'XYZ.2.1.1'
    

    即,在第二次出现“.”后替换数字使用1。

    我知道我的模式是错误的,我目前的sql是:

    select REGEXP_REPLACE ('ABC.1.2.8', '(\.)', '.1.') from dual;
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   revo shanwije    7 年前

    稍后,您可以使用捕获组在替换字符串中引用周围的数字:

    select REGEXP_REPLACE ('ABC.1.2.8', '([0-9])\.[0-9]+\.([0-9])', '\1.1.\2') from dual;
    
        2
  •  1
  •   Jan    7 年前

    你可以使用

    ^([^.]*\.[^.]*\.)\d+(.*)
    

    看见 a demo on regex101.com


    这是:
    ^                # start of the string
    ([^.]*\.[^.]*\.) # capture anything including the second dot
    \d+              # 1+ digits
    (.*)             # the rest of the string up to the end
    

    替换为

    $11$2