sql函数 REGEXP_REPLACE的使用方法小结
目录
- REPLACE
- 案例:
- REGEXP_REPLACE
- 命令格式:
- 参数说明:
- 注意:
- 返回值:
- 常用案例
- 1、用’#‘替换字符串中的所有数字
- Oracle:
- 3、格式化手机号,
- 其他
- 正则符号释义:
REPLACE
假设您的数据在正文中有不必要的空格,您希望用单个空格来替换它们。利用REPLACE函数
案例:
REPLACE函数的参数指定要用一个空格来替换两个空格
SELECT REPLACE('Joe Smith',' ', ' ')

去空格
SELECT REPLACE('Joe Smith',' ', '')

用其他符号

REGEXP_REPLACE
命令格式: regexp_replace(source, pattern, replace_string, occurrence)
参数说明:
● source: string类型,要替换的原始字符串。
● pattern: string类型常量,要匹配的正则模式,pattern为空串时抛异常。
● replace_string:string,将匹配的pattern替换成的字符串。
● occurrence: bigint类型常量,必须大于等于0,
大于0:表示将第几次匹配替换成replace_string,
等于0:表示替换掉所有的匹配子串。
其它类型或小于0抛异常。
注意: Oracle: regexp_replace(source, pattern, replace_string, occurrence) mysql: regexp_replace(source, pattern, replace_string)
返回值:
- 将source字符串中匹配pattern的子串替换成指定字符串后返回,当输入source, pattern,
- occurrence参数为NULL时返回NULL,若replace_string为NULL且pattern有匹配,返回NULL,replace_string为NULL但pattern不匹配,则返回原串。
常用案例
1、用’#‘替换字符串中的所有数字
SELECT regexp_replace('01234abcde56789','[0-9]','#') AS new_str FROM dual;
结果:#####abcde#####

用’#‘替换字符串中的数字0、9
SELECT regexp_replace('01234abcde56789','[09]','#') AS new_str FROM DUAL;
结果:#1234abcde5678#

Oracle: regexp_replace(source, pattern, replace_string, occurrence)

3、格式化手机号,
将+86 13811112222转换为(+86) 138-1111-2222,’+‘在正则表达式中有定义,需要转义。\1表示引用的第一个组
SELECT regexp_replace('+86 13811112222','(\\+[0-9]{2})( )([0-9]{3})([0-9]{4})([0-9]{4})','(\\1)\\3-\\4-\\5');


其他 注意: mysql: regexp_replace(source, pattern, replace_string)

正则符号释义:


到此这篇关于sql函数 REGEXP_REPLACE的使用方法小结的文章就介绍到这了,更多相关sql函数regexp_replace用法内容请搜索电脑手机教程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持电脑手机教程网!