-1

i want to ask how should i modify this expression /^(\+?266)(22|28|57|58|59|27|52)\d{6}$/ so that the evaluated value always start with +266 and 2 digits after that should be 22 or 28 or 57 or 58 or 59 or 27 or 52 followed by 6 random numbers

asked Jan 19, 2022 at 18:35

2 Answers 2

3

It looks like you're almost good to go, except it's not clear why the first ? is in there if you always want to start with +266, also you wrote 37 in the question but have 27 in the regex you included.

Also you didn't say anything about needing capturing groups so you can do away with the first set of brackets. The second set of brackets is required for the 'or' (|) but you can include ?: to make it non-capturing.

Give this a try:

/^\+266(?:22|28|57|58|59|27|52)\d{6}$/gm

You can see it working here:

https://regex101.com/r/ZQqthS/1

answered Jan 19, 2022 at 18:44
Sign up to request clarification or add additional context in comments.

3 Comments

You could also use lists like this: /^\+266(?:2[278]|5[2789])\d{6}$/gm
The ? after the \+ will match the previous token between zero and one times. If the + is required, then you would want to omit it like in your example
thankyou so much @ljdyer
1

Your original regex should basically work. I was about to write the same comments as @Ljdyer, but as he already mentioned it I can save my breath.

In my regexp I used a few character classes, like [28], to shorten it, but that is optional.

const rx=/^\+266(?:2[28]|5[2789]|37)\d{6}$/;
console.log(["+26628123456","+26657763883",
 "+26638123456","+266591234567"]
.map(s=>s.match(rx)));
// the first two will match, the others won't

answered Jan 19, 2022 at 18:49

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.