我想找到一种方法来编写正则表达式来搜索以指定的开始子字符串开头并以另一个指定的结束字符串结尾但总长度最小的字符串的出现次数。例如,如果我的起始字符串是bar
我的结束字符串是foo
当搜索字符串时barbazbarbazfoobazfoo
那么我想让它返回barbazfoo
.
我知道如果它只是一端或另一端的单个字符,例如用我可以搜索的字符替换上面的单词,该怎么做a[^a].*?b
为了找到字符串axb
在字符串内axaxbxb
,但由于我正在寻找单词而不是字符,所以我不能简单地说我不想要任何特定的字母,因为该字母允许出现在中间。
对于上下文,我试图从服务器读取日志,并希望查找例如哪些用户遇到了特定错误,但在用户名出现的位置和有关异常的信息发生的位置之间存在其他信息。因此,我并不是在寻找一个利用以下事实的解决方案:foo
在上面的例子中只出现了字母f
and o
.
附加示例:从第一段开始这个关于前向和后向的正则表达式教程 https://www.regular-expressions.info/lookaround.html
正文如下:
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
,...单独。我想看看如何让它看起来避免子字符串而不是单个字母。