我匹配以下字符串:
使用以下正则表达式:
watermark=(text-\w+\|position-\d+-\d+\|color-([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})\|size-\d+|text-\w+\|position-\d+-\d+\|color-([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})|text-\w+\|position-\d+-\d+|\w+)
它有效,但它太丑了,这让我想用热棒戳我的眼睛。你们这些正则表达的大师是否愿意通过对你的方法的简短解释来重构它?
答案 0 :(得分:1)
watermark=(text-\w+\|position-\d+-\d+(\|color-([0-9a-fA-F]{3}){1,2}(\|size-\d+)?)?|\w+)
由于我(从示例+原始正则表达式)观察到“大小”意味着前面的所有字段都可用,“颜色”意味着前面的所有字段都可用,我只是创建了嵌套可选:
(\|color-([0-9a-fA-F]{3}){1,2}
(\|size-\d+)?
)?
对于([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})
,我“简化”为([0-9a-fA-F]{3}){1,2}
。
答案 1 :(得分:1)
\bwatermark=(?:text-|)\w+(?:\|position-\d+-\d+(?:\|color-[0-9a-fA-F]+(?:\|size-\d+|)|)|)\b
答案 2 :(得分:1)
您可以通过分解软件 http://regexformat.com
运行您的正则表达式之前:
watermark=(text-\w+\|position-\d+-\d+\|color-([A-Fa-f0-9]{3}(?:[A-Fa-f0-9]{3})?)\|size-\d+|text-\w+\|position-\d+-\d+\|color-([A-Fa-f0-9]{3}(?:[A-Fa-f0-9]{3})?)|text-\w+\|position-\d+-\d+|\w+)
之后:
watermark=(?:text-\w+\|position-\d+-\d+(?:\|color-[A-Fa-f0-9]{3}(?:[A-Fa-f0-9]{3})?(?:\|size-\d+)?)?|\w+)
watermark=
(?:
text- \w+ \| position- \d+ - \d+
(?:
\| color- [A-Fa-f0-9]{3}
(?: [A-Fa-f0-9]{3} )?
(?: \| size- \d+ )?
)?
| \w+
)