Search code examples
pythonpython-re

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


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?


Solution

  • 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