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

本文介绍了如何使用Oracle和MySQL的正则表达式功能处理连续数字。在Oracle中,通过regexp_replace函数和非贪婪模式匹配连续数字;而在MySQL中,由于不支持集合方式,采用更简单的regexp_replace函数替换非数字字符。提供的解决方案能够有效地提取和分隔连续的数字串。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一.需求描述

 今天朋友咨询一个正则的需求,对于连续超过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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值