-1

My input is--

Text = "My name is Alex , house no - 254456845 with mobile no. +91-11-22558845 and my account no. is - AB12569BF214558."

Now I want to use regex (re.findall) on my input text and get the expected output.

Expected Output= ( it contains both digits and alphabet and is always of length = 15 )

[ "AB12569BF214558" ]

please help

Chris
  • 29,127
  • 3
  • 28
  • 51

2 Answers2

0
import re
results = re.findall('\\b[A-Z0-9]{15}\\b','''My name is Alex , house no - 254456845 with mobile no. +91-11-22558845 and my account no. is - AB12569BF214558.''')
Matt Miguel
  • 1,325
  • 3
  • 6
  • this solution gives me my expected output in this case, but when i use this code in other cases then i gives me all the strings that have length 15 or more, i just want that string length should be strictly 15 only and not other string with length more than 15 should be given in output. – Lokesh Choraria Jan 05 '21 at 07:44
  • The {15} means exactly 15 characters. Fifteen or more would be {15,} – Matt Miguel Jan 05 '21 at 07:54
  • Oh I think I understand what you mean. The result is only 15 characters, but it is part of a longer string. Adding the '\b' at the start and end per Tim B's answer takes care of that. – Matt Miguel Jan 05 '21 at 07:55
  • @MukulKant Please don't mark code only answers like this. Otherwise you will get banned from reviewing. – 10 Rep Jan 05 '21 at 17:15
0

You should be using the following regex pattern:

\b[A-Z0-9]{15}\b

This will ensure that you match a string of uppercase/numbers which is exactly 15 characters in length. Sample script:

Text = "My name is Alex , house no - 254456845 with mobile no. +91-11-22558845 and my account no. is - AB12569BF214558."
matches = re.findall(r'\b[A-Z0-9]{15}\b', Text)
print(matches)

This prints:

['AB12569BF214558']
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360