Home > Net >  match pattern nth digit of a number using regex
match pattern nth digit of a number using regex

Time:09-30

I am using a regex /^(\ 88)?01[3-9]\d{8}$/

let phoneNum = " 880136486336"

let validRegex = /^(\ 88)?01[3-9]\d{8}$/;

console.log(validRegex.test(phoneNum));

to match a pattern that matches some strings like

 8801712345678
01712345678
01312349876

It works fine but I also want to match 01[n] where n will be 3-9. pattern to find out the mobile network operator.

I want to do something like this

if the number is 01712345678 then print "Network Operator A",

if the number is 8801712345678 then print "Network Operator A"

if the number is 01312349678 then print "Network Operator B"

and different operators for different values of n.

here 017, 013, 014, 016, 015, 019, 018 are mobile operator codes which I want to use to find out operator based on the mobile number.

I don't find any way to do it. How can I do it with regex?

CodePudding user response:

You can capture the three digits at the start with a capturing group, then use String#match or RegExp#exec to get the actual match and then, if there is a match, get the group value and obtain the operator name from a dictionary:

const phones = [' 8801712345678','01712345678','01312349876'];
const operators = {'017' : 'Operator A', '013' : 'Operator C', '014' : 'Operator B', '016' : 'Operator D', '015' : 'Operator E', '019' : 'Operator F', '018' : 'Operator G'};
const validRegex = /^(?:\ 88)?(01[3-9])\d{8}$/; 
for (const phone of phones) {
  const match = validRegex.exec(phone);
  if (match) {
    console.log(phone, "=> Valid, belongs to", operators[match[1]])
  } else {
    console.log(phone,"=> NO MATCH");
  }
}

Here,

  • ^(?:\ 88)?(01[3-9])\d{8}$: the first optional group is now non-capturing and there is a capturing group with ID = 1 now, (01[3-9])
  • validRegex.exec(phone) gets the match object
  • operators[match[1]] returns the Operator name by the key.
  • Related