简体   繁体   English

难以理解此正则表达式的输出

[英]Trouble understanding the output of this regex

I'm trying to create a regex to catch all hexadecimal colors in a string literal. 我正在尝试创建一个正则表达式来捕获字符串文字中的所有十六进制颜色。 I'm using Python 3, and that's what I have: 我正在使用Python 3,这就是我所拥有的:

import re
pattern = re.compile(r"#[a-fA-F\d]{3}([a-fA-F\d]{3})?")

However, when I apply the findall regex method on #abcdef here's what I get: 但是,当我在#abcdef上应用findall regex方法时,得到的是:

>>> re.findall(pattern,"#abcdef") 
["def"] 

Can someone explain me why do I have that? 有人可以解释一下我为什么要这么做吗? I actually need to get ["#abcdef"] Thank you in advance 我实际上需要得到["#abcdef"]预先谢谢

Thanks to Andrej Kesely , I got the answer to my question, that is: 感谢Andrej Kesely ,我得到了我的问题的答案,那就是:

Regex will return capturing group. 正则表达式将返回捕获组。

To bypass this, just change the regex from: 要绕过它,只需将正则表达式从以下位置更改:

r"#[a-fA-F\d]{3}([a-fA-F\d]{3})?"

to: 至:

r"#[a-fA-F\d]{3}(?:[a-fA-F\d]{3})?"

According to http://regex101.com : 根据http://regex101.com 正则表达式说明

It looks like this regex is looking for 看起来这个正则表达式正在寻找

#(three characters a through f, A through F or a digit)(three characters a through f, A through F or a digit, which may or may not be present, and if they are they are what is returned from the match) #(三个字符a到f,A到F或一个数字)(三个字符a到f,A到F或一个数字,可能存在也可能不存在,如果是,则是从比赛中返回的字符)

If you are looking to match any instance of the whole above string, I would recommend this instead: 如果您希望匹配上述整个字符串的任何实例,则建议改为:

#[a-fA-F\\d]{6} 在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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