您可以使用与 left/center/right 匹配的正则表达式和一系列交替。
条件用于匹配部分,无论它们在行中出现的顺序如何。
这样就可以匹配其中的 1、2 或 3 个。
更新
已修改以匹配每个部分,直到下一个部分(如果存在)。
基于这里的条件信息 -> http://www.rexegg.com/regex-conditionals.html
如果它的 python/PCRE 这应该可以工作:
(?:(?:[^&]|&[\S\s])*?(?:&L(?P<left>(?(left)(?!))(?:[^&]|&[^LCR])*)|&C(?P<center>(?(center)(?!))(?:[^&]|&[^LCR])*)|&R(?P<right>(?(right)(?!))(?:[^&]|&[^LCR])*))){1,3}
如果它的 Perl/PCRE,这可行:
# (?:(?:[^&]|&[\S\s])*?(?:&L(?<left>(?(<left>)(?!))(?:[^&]|&[^LCR])*)|&C(?<center>(?(<center>)(?!))(?:[^&]|&[^LCR])*)|&R(?<right>(?(<right>)(?!))(?:[^&]|&[^LCR])*))){1,3}
(?:
(?: [^&] | & [\S\s] )*? # Get all possible quoted &&
# even &[LCR] if needed
(?: # Get one of &L or &C or &R
&L
(?<left> # (1), Left
(?(<left>)
(?!) # Allow only 1 left
)
(?: [^&] | & [^LCR] )* # Get all possible quoted && up to but not &[LCR]
)
|
&C
(?<center> # (2), Center
(?(<center>)
(?!) # Allow only 1 center
)
(?: [^&] | & [^LCR] )*
)
|
&R
(?<right> # (3), Right
(?(<right>)
(?!) # Allow only 1 right
)
(?: [^&] | & [^LCR] )*
)
)
){1,3} # Do 1 to 3 times
输出:
** Grp 0 - ( pos 0 , len 132 )
&L&"Lucida Grande,Standard"&K000000Left top&C&"Lucida Grande,Standard"&K000000Middle top&R&"Lucida Grande,Standard"&K000000Right top
** Grp 1 - ( pos 2 , len 41 )
&"Lucida Grande,Standard"&K000000Left top
** Grp 2 - ( pos 45 , len 43 )
&"Lucida Grande,Standard"&K000000Middle top
** Grp 3 - ( pos 90 , len 42 )
&"Lucida Grande,Standard"&K000000Right top