In: Computer Science
Python regex
How to write the regex in Python that only include the contents within a parentheses?
e.g. "uio" [ek3k 0die] 4229834
return "ek3k 0die"
How to write the regex in Python that only include the contents within a parentheses?
e.g. "uio" [ek3k 0die] 4229834
return "ek3k 0die"
code to get the content within the bracket
save the file with .py extension
or execute in python console:
Code
import re #regular expression module imported
a='"uio" [ek3k 0die] 4229834' # declare your string
o=re.search(r"\[((\w*\s*\w*)*)\]",a,re.X) # we will use search function to match the regular o.group(1) # to access search object by group method #expression
**********************************************************
regular expression explanation
it shoud contain open square bracket parentheses and followed by any charater and any number of times and ends with closed square bracket parentheses
* => it indicates 0 or more times occurences
/[ ( (\w* \s* \w*)* ) \]
first open bracket then any character any number of times(denoted by \w* ) any number of spaces (\s*) any number of characters (\w*) and whole * to repeat the pattern.
output:
DONT FORGET TO IMPORT RE