0
votes

Say i give a pattern 123* or 1234* , i would like to match any 10 digit number that starts with that pattern. It should have exactly 10 digits.

Example:

Pattern : 123 should match 1234567890 but not 12345678

I tried this regex : (^(123)(\d{0,10}))(?(1)\d{10}).. obviously it didn't work. I tried to group the pattern and remaining digits as two different groups. It matches 10 digits after the captured group (https://regex101.com/). How do i check the captured group is exactly 10 digits? Or is there any good knacks here. Please guide me.

2
It is diffiuclt to help if you do not explain the real life scenario, and provide the code you have trouble with. Maybe you need (?<!\d)123\d{7}(?!\d)Wiktor Stribiżew
I was trying to block phone numbers that start with certain pattern. The users set any blocking pattern like 123* or 43* etc.. so i need to block all inbound and outbound that matches that pattern. But before hanging up i need to know why the call failed is it because they dialed wrong number of digits or blocked pattern to set the message properly. This regex \b(?=123)\d{10}\b by @randomir seems to have solved that. Thanks for your thoughts in helping solving that.Anandan

2 Answers

2
votes

Sounds like a case for the positive lookahead:

(?=123)\d{10}

This will match any sequence of exactly 10 digits but only if prefixed with 123. Test it here.

Similarly for prefix 1234:

(?=1234)\d{10}

Of course, if you know the prefix length upfront, you can use 123\d{7}, but then you'll have to change range limits with each prefix change (for example: 1234\d{6}).


Additionally, to ensure only isolated groups of 10 digits are captured, you might want to anchor the above expression with a (zero-length) word boundary \b:

\b(?=123)\d{10}\b

or, if your sequence can appear inside of the word, you might want to use negative lookbehind and lookahead on \d (as suggested in comments by @Wiktor):

(?<!\d)(?=123)\d{10}(?!\d)
1
votes

I would keep it simple:

import re

text = "1234567890"

match = re.search("^123\d{7}$|^1111\d{6}$", text)
if match:
    print ("matched")

Just throw your 2 patterns in as such and it should be good to go! Note that 123* would catch 1234* so I'm using 1111\d{6} as an example