简体   繁体   中英

using regex to find same digit phone numbers

I need to find same digit phone numbers from a table and delete these. Phone Numbers are like below :

+999999999999
11111111
0000000000000
44444444

I am following this answer to solve this. I am trying :

select * from tblPhone where PhoneNo like  '^([0-9a-z])\1+$'

But not succeed. PhoneNo is varchar. How I can achieve this ?

Try this:

select *
from tblPhone
where 
substring(replace(PhoneNo,'+',''),1,len(replace(PhoneNo,'+',''))-1) 
= substring(replace(PhoneNo,'+',''),2,len(replace(PhoneNo,'+','')))

The idea is that if substring from 1st to second-last position matches the one from 2nd to last, the string must be composed of identical characters.

Demo

Here is an idea. There is a problem with the first character, which can be a + or number. Let's substitute the second character for an empty string and look at the result:

where replace(PhoneNo, substring(PhoneNo, 2, 1), '') in ('+', '') and
      (PhoneNo not like '%[^0-9]%' and PhoneNo like '[0-9]%'or
       PhoneNo not like '+%[^0-9]%') and PhoneNo like '+%'
      )

You can do a pattern matching in SQL Server using patindex but regular expressions as such are not directly supported. There is hope, however, if you use .Net and CLR user-defined functions .

create table #temp(col1 varchar(25))

insert into #temp values ('+9999999')

insert into #temp values ('+123456789')

insert into #temp values ('+444444444')

insert into #temp values ('+9840536987')

select * from #temp

begin tran
select * from #temp

delete from #temp where cast(replace(replace(col1,'+',''),RIGHT(replace(col1,'+',''),1),0) as bigint) = 0

select * from #temp
rollback tran 在此处输入图片说明

You can try this:

SELECT *
  FROM tblPhone
WHERE 
  CAST(PhoneNo AS BIGINT) = REPLICATE(RIGHT(PhoneNo, 1), LEN(CAST(PhoneNo AS BIGINT)))

OR

SELECT *
FROM   tblPhone
WHERE  REPLACE(PhoneNo, RIGHT(PhoneNo, 1),'') IN ('+','')

This generates the set all the possible invalid phone numbers (which is a very small number) and joins that to tblPhone. This is more efficient than doing string manipulations on every phone number in the table.

DELETE t1
FROM tblPhone t1
INNER JOIN (VALUES (''),('+')) t2(prefix)
  CROSS JOIN (VALUES('0'),('1'),('2'),('3'),('4'),('5'),('6'),('7'),('8'),('9')) t3(digit)
  CROSS JOIN (SELECT TOP (13) ROW_NUMBER() OVER(ORDER BY (SELECT 1)) FROM master.dbo.spt_values) t4(n)
ON PhoneNo = prefix+REPLICATE(digit,n)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM