简体   繁体   English

正则表达式匹配忽略非数字的电话号码

[英]Regex to match a phone number ignoring non digits

Im trying to match a phone number in regex when there is a non standard format in the data.当数据中存在非标准格式时,我试图匹配正则表达式中的电话号码。 How would you write a regex to match 0408111 in all 4 of these examples?您将如何编写一个正则表达式来匹配所有 4 个示例中的 0408111?

(04) 0811 111
0408-111111
0408111111
0a4b0c8d1e1f1g

The best I came up with is:我想到的最好的是:

/0[^\d]*4[^\d]*0[^\d]*8[^\d]*1[^\d]*1[^\d]*1/g

But is there a better way?但是有更好的方法吗?

 var haystack = ` (04) 0811 111 0408-111111 0408111111 0a4b0c8d1e1f1g `; var needle = /0[^\d]*4[^\d]*0[^\d]*8[^\d]*1[^\d]*1[^\d]*1/g; var result = haystack.match(needle); console.log(result);

Given the example string from your question.给出您问题中的示例字符串。

let haystack = `
(04) 0811 111
0408-111111
0408111111
0a4b0c8d1e1f1g
`

One solution to return the string '0408111' each time digits appear in this order within each line of haystack whilst discounting any non-numerical interspersed within each line would be to:每次在haystack的每一行中按此顺序出现数字时返回字符串'0408111'同时忽略散布在每一行中的任何非数字的一种解决方案是:

  1. Remove any non-numerical characters from haystackhaystack中删除任何非数字字符
  2. Return all matches of the pattern /0408111/g返回模式/0408111/g的所有匹配项
let result = haystack.replace(/[^\d\n]/g, '').match(/0408111/g)

Given haystack as above, result will be [ '0408111', '0408111', '0408111', '0408111' ] .给定haystack如上所述, result将是[ '0408111', '0408111', '0408111', '0408111' ]

Since you say that you are using this to search for phone numbers within each line of the input string and the example you gave in your question is seeking a match on 7 consecutive digits in each line regardless of any non-numeric characters.由于您说您正在使用它在输入字符串的每一行中搜索电话号码,并且您在问题中给出的示例是在每行中的 7 个连续数字上寻求匹配,而不管任何非数字字符。 The above code could be adjusted as to match the first 7 digits in each line once non-numeric characters have been removed - by matching on /\d{7}/g instead /0408111/g pattern.一旦非数字字符被删除,上面的代码可以调整为匹配每行中的前 7 位数字 - 通过匹配/\d{7}/g而不是/0408111/g模式。

eg例如

let haystack = `
(04) 0811 111
0454-14717181
0768551351111
0tY4lopj9pjo5567
0a4b0c8d1e1f1g
123456
`

let result = haystack.replace(/[^\d\n]/g, '').match(/\d{7}/g)

Here result will be [ '0408111', '0454147', '0768551', '0495567', '0408111' ]这里的result将是[ '0408111', '0454147', '0768551', '0495567', '0408111' ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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