简体   繁体   中英

Python RegEx to find a string between < and >

I have a Python application where I am trying to parse out information between < and > in a string.

My string is:

##MESSAGE=<A=test_id,B=.,C=type,D="Description">\n

I have tried the Python :

pattern = re.compile('*\<(\w+)\>*')
match = pattern.match(line)

but my pattern still does not appear to be correct because match always equals None .

Can anyone see what the issue is in my pattern?

pattern = re.compile('<(\w+)>')

or

pattern = re.compile('<([^>]*)>')

You can use the patterns like this way:

using re.search()

x = re.search(pattern, input)
print x.group(1)

using re.match() : you have to add .* at the both ends of the regex. See the example:

pattern = re.compile('.*<([^>]*)>.*')
#                     ^^         ^^
x = pattern.match(input)
print x.group(1)

请改用re.searchre.match尝试从行首开始进行匹配。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM