How to find a number enclosed in square brackets followed by a string?

Question:

I am trying to get the numbers enclosed in square brackets that are preceded by a string. The search should be based on the phonenumber and not the first [] square brackets.

mystring = 'my name is raj and my phoneNumber [12343567890] , pincode[123]'
expected=1234567890

I tried the following but it is not fetching the right values

re.search(r'^phoneNumber [s*+?(-?d+)s*]', mystring ).group(0) 

can anyone help me with the code?

Asked By: Maharajaparaman

||

Answers:

I am trying to get the numbers enclosed in a square brackets that is preceded by a string.

Try the below (no regexp)

mystring = 'my name is raj and my phoneNumber [12343567890] , pincode[123]'
left = mystring.find('[')
right = mystring.find(']')
num = mystring[left + 1:right]
print(num)

output

12343567890
Answered By: balderman

You can use this answer [1] and add the string phoneNumber to the regex:

import re

s = "my name is raj and my phoneNumber [12343567890] , pincode[123]"
m = re.search(r"phoneNumber [([A-Za-z0-9_]+)]", s) 
print(m.group(1))

[1] Get the string within brackets in Python

Answered By: buddemat
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.