Extract text from regular expression?

I am trying to get the results of some consistent text in a regular expression, but it does not seem to work. Does anyone know what could be wrong?

import re
text = "I want to match anything in <angle brackets>"
match = re.search("\<(?P<brackets>[^\>]+)>", text)
if match:
    print (match.group('brackets'))

This does not print anything, i.e. no match found.

+4
source share
2 answers

This is indeed a very common mistake - it seems you use re.matchit when you want to use it re.search. re.matchmatches only the beginning of the given text, while it re.searchchecks the whole thing.

import re
text = "I want to match anything in <angle brackets>"
match = re.search("\<(?P<brackets>[^\>]+)>", text)
if match:
    print (match.group('brackets'))

Output:

'angle brackets'
+6
source

@Tom Jacques , , , , , . :

import re
text = "I want to match anything in <angle brackets>"
match = re.search("\<(?P<brackets>.*)\>",text)
if match:
    print (match.group('brackets'))

[^ .*) text re.search().

()

, ​​ , . > , >.

+2

All Articles