简体   繁体   中英

RegEx for matching N-digit plus consecutive numbers

I am trying to clean input strings using javascript on node.js. some input strings might contain phone numbers (or random sequence of numbers) which I would like to remove. For example:

Input String: Terrace 07541207031 RDL 18.02

after cleaning I would like the string to be: Terrace RDL 18.02

I would like to detect numbers (say greater than 4 digits) and remove it.

This expression likely matches your desired inputs.

(\s)([0-9]{4,})(\s?)

If you wish to match any 4 digit plus numbers, you can simply remove the left and right space check boundaries:

([0-9]{4,})

JavaScript Demo

 const regex = /(\\s)([0-9]{4,})(\\s?)/gm; const str = `Terrace 07541207031 RDL 18.02 Terrace 07541 RDL 18.02 Terrace 075adf8989 RDL 18.02 Terrace 075adf898 RDL 18.02 075898 RDL 18.02 Terrace RDL 98989https://regex101.com/r/FjZqaF/1/codegen?language=javascript`; let m; while ((m = regex.exec(str)) !== null) { // This is necessary to avoid infinite loops with zero-width matches if (m.index === regex.lastIndex) { regex.lastIndex++; } // The result can be accessed through the `m`-variable. m.forEach((match, groupIndex) => { console.log(`Found match, group ${groupIndex}: ${match}`); }); } 

Performance Test

This script returns the runtime of your input string against the expression.

 const repeat = 1000000; const start = Date.now(); for (var i = repeat; i >= 0; i--) { const regex = /(.*\\s)([0-9]{4,})(\\s.*)/gm; const str = "Terrace 07541207031 RDL 18.02"; const subst = `$1$3`; var match = str.replace(regex, subst); } const end = Date.now() - start; console.log("YAAAY! \\"" + match + "\\" is a match 💚💚💚 "); console.log(end / 1000 + " is the runtime of " + repeat + " times benchmark test. 😳 "); 

RegEx

If this was not your desired expression, you can modify/change your expressions in regex101.com .

RegEx Circuit

You can also visualize your expressions in jex.im :

在此处输入图片说明

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