简体   繁体   中英

Get second occurrence of match from pythons positive lookbehind assertion

I want to get the first and the second occurrence of a match in a string with python regex.

The string is : QPushButton {background-color: #FF123456;color: #FF654321; border: none;outline: none;}QPushButton:pressed {background-color: #FF123456;} QPushButton {background-color: #FF123456;color: #FF654321; border: none;outline: none;}QPushButton:pressed {background-color: #FF123456;}

The Regex is: (?<=color:)(([\\w\\ \\#])*)

On runing the code width:

 match = re.search(regEx, string)
 if match:
     match.groups()

I get as result only (' #FF0B9DF7', '7'). How can i get the second occurrence ( '#F654321') of the color?

By using the correct function and accessing the result.

>>> re.findall(needle, haystack)
[(' #FF123456', '6'), (' #FF654321', '1'), (' #FF123456', '6')]

As others have pointed out, re.findall is the method to use. But I'm not sure about your search pattern either... are you sure you want to get a list of tuples, with the first item containing a leading space and the second item being the last character in each match? If all you want is the color strings, I would do it like this:

regEx = r"(?<=color:)\s*(#[0-9A-Za-z]+)"
match = re.findall(regEx, string)
match
['#FF123456', '#FF654321', '#FF123456']

Now we just have a list of strings, that should be easier to work with than what you got before.

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