暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

正则案例三:匹配3个及以上连续数字并输出

原创 只是甲 2021-06-22
1244

一.需求描述

 今天朋友咨询一个正则的需求,对于连续超过3个数字进行输出,如果有多个连续数字,都需要输出。
 例如 123abc1234 输出为 123.1234,中间用’.'进行分隔。

二.解决方案

2.1 Oracle解决方案

看到这个需求,首先想到的是使用Oracle 正则表达式的regexp_replace函数了。

多个匹配表达式用()进行关联,例如(.*?)([0-9]{3,})
其中 *? 是匹配0次或多次,非贪婪模式。
[0-9]{3,} 是匹配连续3个及以上数字。

代码:

with tmp1 as ( select 'abc12' str from dual union select 'abc123' str from dual -- OK union select '1234abc333' str from dual ) select regexp_replace(str,'(.*?)([0-9]{3,})(.*?)', '\2.') str_new from tmp1 where regexp_like(str,'[0-9]{3}')

测试记录:

SQL> with tmp1 as 2 ( 3 select 'abc12' str from dual 4 union 5 select 'abc123' str from dual -- OK 6 union 7 select '1234abc333' str from dual 8 ) 9 select regexp_replace(str,'(.*?)([0-9]{3,})(.*?)', '\2.') str_new 10 from tmp1 11 where regexp_like(str,'[0-9]{3}') 12 / STR_NEW -------------------------------------------------------------------------------- 1234.333. 123.

2.2 MySQL 解决方案

 用MySQL 8.0版本进行测试,发现MySQL不支持()这种集合的方式,我找到了一种更为简便的解决方案,使用regexp_replace函数。

代码:

with tmp1 as ( select 'abc12' str from dual union select 'abc123' str from dual -- OK union select '1234abc333' str from dual ) select regexp_replace(str,'[^0-9]{1,}', '.') str_new from tmp1 where regexp_like(str,'[0-9]{3}')

测试记录:

mysql> with tmp1 as -> ( -> select 'abc12' str from dual -> union -> select 'abc123' str from dual -- OK -> union -> select '1234abc333' str from dual -> ) -> select regexp_replace(str,'[^0-9]{1,}', '.') str_new -> from tmp1 -> where regexp_like(str,'[0-9]{3}') -> ; +----------+ | str_new | +----------+ | .123 | | 1234.333 | +----------+ 2 rows in set (0.00 sec)
「喜欢这篇文章,您的关注和赞赏是给作者最好的鼓励」
关注作者
【版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

文章被以下合辑收录

评论