0

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?

Maharajaparaman
  • 113
  • 2
  • 11
  • 1
    Does this answer your question? [Get the string within brackets in Python](https://stackoverflow.com/questions/8569201/get-the-string-within-brackets-in-python) – sushanth Nov 05 '20 at 07:45
  • @sushanth tried it but it is not working for my case. that is why i added this qn – Maharajaparaman Nov 05 '20 at 07:46

2 Answers2

2

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

buddemat
  • 3,262
  • 10
  • 15
  • 39
  • Glad I could help! In case you're interested, using comments just to say 'thank you' is discouraged on SO (see https://stackoverflow.com/help/someone-answers). But you're welcome all the same ;) – buddemat Nov 05 '20 at 08:11
1

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
balderman
  • 21,028
  • 6
  • 30
  • 43