简体   繁体   中英

Regular Expression to find <>

I have a string

"Absolutely<U+653C><U+3E64><U+613C><U+3E30><U+623C><U+3E64><U+653C><U+3E64><U+623C><U+3E31><U+383C><U+3E64> Friendship goals exceeded here!! Sydney, Melbourne, Connecticut &amp; South Carolina<U+653C><U+3E64><U+613C><U+3E30><U+623C><U+3E64><U+653C><U+3E64><U+623C><U+3E31><U+383C><U+3E61>\r\n"

I want to separate only the <> part from the string. I tried <.*> but it returned

<U+653C><U+3E64><U+613C><U+3E30><U+623C><U+3E64><U+653C><U+3E64><U+623C><U+3E31><U+383C><U+3E64> Friendship goals exceeded here!! Sydney, Melbourne, Connecticut &amp; South Carolina<U+653C><U+3E64><U+613C><U+3E30><U+623C><U+3E64><U+653C><U+3E64><U+623C><U+3E31><U+383C><U+3E61>

I dont want the words between them. I want the output as,

 ["<U+653C><U+3E64><U+613C><U+3E30><U+623C><U+3E64><U+653C><U+3E64><U+623C><U+3E31><U+383C><U+3E64>", "<U+653C><U+3E64><U+613C><U+3E30><U+623C><U+3E64><U+653C><U+3E64><U+623C><U+3E31><U+383C><U+3E61>"]

Any help. I'm stuck in python.

You need a negative lookahead . This pattern matches until it finds the first > not followed by a < :

import re

text = "Absolutely<U+653C><U+3E64><U+613C><U+3E30><U+623C><U+3E64><U+653C><U+3E64><U+623C><U+3E31><U+383C><U+3E64> Friendship goals exceeded here!! Sydney, Melbourne, Connecticut &amp; South Carolina<U+653C><U+3E64><U+613C><U+3E30><U+623C><U+3E64><U+653C><U+3E64><U+623C><U+3E31><U+383C><U+3E61>\r\n"

pattern = "<.*?>(?!<)"

print re.findall(pattern, text)
#['<U+653C><U+3E64><U+613C><U+3E30><U+623C><U+3E64><U+653C><U+3E64><U+623C><U+3E31><U+383C><U+3E64>', '<U+653C><U+3E64><U+613C><U+3E30><U+623C><U+3E64><U+653C><U+3E64><U+623C><U+3E31><U+383C><U+3E61>']

You can use <.*?>(?!<) instead of <.*> .

This is what you may do

s = "Absolutely<U+653C><U+3E64><U+613C><U+3E30><U+623C><U+3E64><U+653C><U+3E64><U+623C><U+3E31><U+383C><U+3E64> Friendship goals exceeded here!! Sydney, Melbourne, Connecticut &amp; South Carolina<U+653C><U+3E64><U+613C><U+3E30><U+623C><U+3E64><U+653C><U+3E64><U+623C><U+3E31><U+383C><U+3E61>\r\n"

result = re.findall('<.*?>(?!<)',s)

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