I am having some trouble with Python giving me a result I do not expect. Here is a sample code :
number = re.search(" [0-9] ", "test test2 test_ 2 333")
print number.groups()
number = re.search(" [[:digit:]] ", "test test2 test_ 2 333")
print number.groups()
In the first block I get an object returned but with nothing in it. Where I think I should get the string “2”.
In the second block I don’t even get an object, where I am expection the string “2”.
While when I do this in bash everything looks fine :
echo "test test2 test_ 2 333" | grep " [[:digit:]] "
echo "test test2 test_ 2 333" | grep " [0-9] "
Can somebody help me please?
The groups() method returns the capture groups. It does not return group 0, in case that’s what you were expecting. Use parens to indicate capture groups. eg:
For your second example, Python’s re module doesn’t recognize the “[:digit:]” syntax. Use
\d. eg: