Python regex matches text between quotes

In the following script, I would like to pull the text between double quotes ("). However, the python interpreter is not happy, and I cannot understand why ...

import re text = 'Hello, "find.me-_/\\" please help with python regex' pattern = r'"([A-Za-z0-9_\./\\-]*)"' m = re.match(pattern, text) print m.group() 

The output should be find.me-/\ .

+6
source share
4 answers

match starts the search at the beginning of the text.

Use search instead:

 #!/usr/bin/env python import re text = 'Hello, "find.me-_/\\" please help with python regex' pattern = r'"([A-Za-z0-9_\./\\-]*)"' m = re.search(pattern, text) print m.group() 

match and search return None if they do not match.

I assume you get AttributeError: 'NoneType' object has no attribute 'group' from python: this is because you assume that you will match without checking the return from re.match .

+11
source

Use re.search() instead of re.match() . The latter will only match at the beginning of the lines (e.g. implicit ^ ).

+1
source

You need re.search() , not re.match () `, which is bound to the beginning of your input string.

Docs here

+1
source

If you write:

 m = re.search(pattern, text) 

match : search at the beginning of the text

search : search the entire line

Maybe this will help you understand: http://docs.python.org/library/re.html#matching-vs-searching

+1
source

Source: https://habr.com/ru/post/907346/


All Articles