我希望找到一种方法来编写正则表达式来搜索字符串的出现,该字符串以指定的开始子字符串开头,以另一个指定的结束字符串结尾,但其总长度最小。例如,如果我的起始字符串是bar,而我的结束字符串在搜索字符串barbazbarbazfoobazfoo时是foo,那么我想让它返回barbazfoo。
我知道如何做到这一点,如果它只是一个字符在一端或另一端,例如,在替换上面的字符,我可以使用a[^a].*?b搜索,以找到字符串axb在字符串axaxbxb,但由于我是寻找单词,而不是字符,我不能简单地说,我不想要任何一个特定的字母,因为字母是允许出现在中间。
对于上下文,我试图从服务器读取日志,并希望找到例如哪些用户遇到了特定的错误,但是在用户名出现的位置和异常发生的位置之间还有其他信息。因此,我并不是在寻找使用以下事实的解决方案:在上面的示例中,foo只有f和o两个字母出现。
附加示例:取自关于这个regex教程是关于前瞻性和前瞻性的。的第一段
案文如下:
Lookahead and lookbehind, collectively called "lookaround", are zero-length assertions just like the start and end of line, and start and end of word anchors explained earlier in this tutorial. The difference is that lookaround actually matches characters, but then gives up the match, returning only the result: match or no match. That is why they are called "assertions". They do not consume characters in the string, but only assert whether a match is possible or not. Lookaround allows you to create regular expressions that are impossible to create without them, or that would get very longwinded without them.
如果我的起始词是lookaround,而我的结束词是match,那么我希望已经找到子字符串lookaround actually match,注意到目标单词可能会多次出现,并且可能与目标单词共享字符之间的单词和字符数目未知。例如,在上面的示例中,lookaround[^lookaround]*?match返回到没有找到匹配的位置,因为语法似乎是为了避免每个字母l、o、k、.单独的。我想看看怎样才能让它看起来像避免子串,而不是单个字母。
https://stackoverflow.com/questions/56415304
复制相似问题