How to extract a substring from inside a string in Python?

PythonServer Side ProgrammingProgramming

You can use group capturing in regular expressions to extract a substring from inside a string. You need to know the format and surrounding of the substring you want to extract. For example if you have a line and want to extract money information from it with the format $xxx,xxx.xx you can use the following:

import re
text = 'The phone is priced at $15,745.95 and has a camera.'
m ='(\$[0-9\,]*.[0-9]{2})', text)
if m:

This will give the output:


The actual regex will depend on the conditions of your use case.

Published on 14-Dec-2017 15:07:46