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?
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
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))
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?
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
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))