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

Maharajaparaman
  • 141
  • 3
  • 12
  • 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
  • In your own words, where the code says `r'^phoneNumber \[\s*\+?(-?\d+)\s*\]'`, what do you think the `^` means? Do you see how this interferes with the intended regex search? (Hint: is the desired text at the start of the string?) – Karl Knechtel Dec 30 '22 at 22:40

2 Answers2

1

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
  • 4,552
  • 14
  • 29
  • 49
0

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
  • 22,927
  • 7
  • 34
  • 52