鉴于:
ABC
content 1
123
content 2
ABC
content 3
XYZ
是否可以创建与“ABC[\W\w]+?XYZ”的最短版本匹配的正则表达式
本质上,我正在寻找“ABC 后跟任何以 XYZ 结尾的字符,但如果我在两者之间遇到 ABC 则不匹配”(但将 ABC 视为潜在的正则表达式本身,因为它并不总是固定长度。 ..so ABC 或 ABcC 也可以匹配)
因此,更一般地说:REGEX1 后跟任何字符并由 REGEX2 终止,如果 REGEX1 出现在两者之间,则不匹配。
在这个例子中,我不想要前 4 行。
(我相信这个解释可能需要......进一步解释哈哈)
编辑:
好吧,我认为现在需要进一步解释!感谢您迄今为止的建议。在我开始研究如何将您提出的每个解决方案应用于我的问题时,我至少会给您更多的思考。
建议1:颠倒字符串内容和正则表达式。
这当然是一个非常有趣的 hack,它根据我的解释解决了问题。在简化问题时,我也没有提到同样的事情可能会反过来发生,因为结束签名也可能在以后存在(并且已证明在我的具体情况下)。这引入了如下所示的问题:
ABC
content 1
123
content 2
ABC
content 3
XYZ
content 4
MNO
content 5
XYZ
In this instance, I would check for something like "ABC through XYZ" meaning to catch [ABC, content 1, XYZ]...but accidentally catching [ABC, content 1, 123, content 2, ABC, content 3, XYZ]. Reversing that would catch [ABC, content 3, XYZ, content 4, MNO, content 5, XYZ] instead of the [ABC, content 2, XYZ] that we want again. The point is to try to make it as generalized as possible because I will also be searching for things that could potentially have the same starting signature (regex "ABC" in this case), and different ending signatures.
If there is a way to build the regexes so that they encapsulate this sort of limitation, it could prove much easier to just reference that any time I build a regex to search for in this type of string, rather than creating a custom search algorithm that deals with it.
Proposal 2: A+B+C+[^A]+[^B]+[^C]+XYZ with IGNORECASE flag
This seems nice in the case that ABC is finite. Think of it as a regex in itself though. For example:
Hello!GoodBye!Hello.Later.
VERY simplified version of what I'm trying to do. I would want "Hello.Later." given the start regex Hello[!.] and the end Later[!.]. Running something simply like Hello[!.]Later[!.] would grab the entire string, but I'm looking to say that if the start regex Hello[!.] exists between the first starting regex instance found and the first ending regex instance found, ignore it.
The convo below this proposal indicates that I might be limited by regular language limitations similar to the parentheses matching problem (Google it, it's fun to think about). The purpose of this post is to see if I do in fact have to resort to creating an underlying algorithm that handles the issue I'm encountering. I would very much like to avoid it if possible (in the simple example that I gave you above, it's pretty easy to design a finite state machine for...I hope that holds as it grows slightly more complex).
Proposal 3: ABC(?:(?!ABC).)*?XYZ with DOTALL flag
I like the idea of this if it actually allows ABC to be a regex. I'll have to explore this when I get in to the office tomorrow. Nothing looks too out of the ordinary at first glance, but I'm entirely new to python regex (and new to actually applying regexes in code instead of just in theory homework)