Oracle中使用正则表达式

  1. regexp_like

    regexp_like 只能用于条件表达式,和 like 类似,但是使用的正则表达式进行匹配

    语法: REGEXP_LIKE(srcstr, pattern [,match_option])

    1. srcstr : 搜索值
    2. pattern : 正则表达式
    3. match_option : 匹配选项,可以包含一个或多个
      • “c” : 使用区分大小写的匹配(默认值)
      • “i” : 使用不区分大小写的匹配
      • “n” : 允许匹配任何字符的运算符来匹配换行符
      • “m” : 将源字符串作为多行处理
    select str from tmp where id='like' and regexp_like(str,'A\d+','i');
  2. regexp_substr

    regexp_substr 函数,和 substr 类似,截取符合正则匹配的字符串

    语法:REGEXP_SUBSTR(srcstr, pattern [, position [, occurrence [, match_option]]])

    1. position : 搜索的起始位置
    2. occurrence : 搜索的匹配项
    3. match_option : 匹配选项,可以包含一个或多个
      • “c” : 使用区分大小写的匹配(默认值)
      • “i” : 使用不区分大小写的匹配
      • “n” : 允许匹配任何字符的运算符来匹配换行符
      • “m” : 将源字符串作为多行处理
    select
    str,
    regexp_substr(str,'[^,]+') str,
    regexp_substr(str,'[^,]+',1,1) str,
    regexp_substr(str,'[^,]+',1,2) str,
    regexp_substr(str,'[^,]+',2,1) str
    from tmp
    where id='substr';
  3. regexp_instr

    regexp_instr函数, 和 instr 类似,用于标定正则匹配的字符子串的开始位置

    语法:REGEXP_INSTR(srcstr, pattern [, position [, occurrence[, return_option [, match_option]]]])

    1. srcstr : 搜索值
    2. pattern : 正则表达式
    3. position : 搜索的起始位置
    4. occurrence : 搜索的匹配项
    5. return_option : 匹配项的开头或结尾位置
    6. match_option : 匹配选项,可以包含一个或多个
      • “c” : 使用区分大小写的匹配(默认值)
      • “i” : 使用不区分大小写的匹配
      • “n” : 允许匹配任何字符的运算符来匹配换行符
      • “m” : 将源字符串作为多行处理
    select
    str,
    regexp_instr(str,'\.' ) ind ,
    regexp_instr(str,'\.',1,2) ind ,
    regexp_instr(str,'\.',5,2) ind
    from tmp where id='instr';
  4. regexp_replace

    regexp_replace 函数,和 replace 类似,用于替换符合正则表达式的字符串

    语法:REGEXP_REPLACE(srcstr, pattern [,replacestr [, position[, occurrence [, match_option]]]])

    1. srcstr : 搜索值
    2. pattern : 正则表达式
    3. replacestr : 替换模式的字符串
    4. position : 搜索的起始位置
    5. occurrence : 搜索的匹配项
    6. match_option : 匹配选项,可以包含一个或多个
      • “c” : 使用区分大小写的匹配(默认值)
      • “i” : 使用不区分大小写的匹配
      • “n” : 允许匹配任何字符的运算符来匹配换行符
      • “m” : 将源字符串作为多行处理
    select
    str,
    regexp_replace(str,'020','GZ') str,
    regexp_replace(str,'(\d{3})(\d{3})','<\2\1>') str
    -- 将第一、第二捕获组交换位置,用尖括号标识出来
    from tmp
    where id='replace';