Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Trích substring từ bên trong string Python

Dùng group capturing trong regular expression trích substring từ bên trong string. Cần biết format và surrounding của substring muốn trích. Ví dụ, có line muốn trích money info format $xxx,xxx.xx:

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

Output:

$15,745.95

Regex thực tế tùy điều kiện use case.