首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用起始词和结束词查找最短字符串

用起始词和结束词查找最短字符串
EN

Stack Overflow用户
提问于 2019-06-02 13:01:26
回答 1查看 703关注 0票数 2

我希望找到一种方法来编写正则表达式来搜索字符串的出现,该字符串以指定的开始子字符串开头,以另一个指定的结束字符串结尾,但其总长度最小。例如,如果我的起始字符串是bar,而我的结束字符串在搜索字符串barbazbarbazfoobazfoo时是foo,那么我想让它返回barbazfoo

我知道如何做到这一点,如果它只是一个字符在一端或另一端,例如,在替换上面的字符,我可以使用a[^a].*?b搜索,以找到字符串axb在字符串axaxbxb,但由于我是寻找单词,而不是字符,我不能简单地说,我不想要任何一个特定的字母,因为字母是允许出现在中间。

对于上下文,我试图从服务器读取日志,并希望找到例如哪些用户遇到了特定的错误,但是在用户名出现的位置和异常发生的位置之间还有其他信息。因此,我并不是在寻找使用以下事实的解决方案:在上面的示例中,foo只有fo两个字母出现。

附加示例:取自关于这个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返回到没有找到匹配的位置,因为语法似乎是为了避免每个字母lok、.单独的。我想看看怎样才能让它看起来像避免子串,而不是单个字母。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-06-02 13:41:01

你必须使用温和的贪婪的象征:

第一(有字界)

代码语言:javascript
复制
\blookaround\b(?:(?!\b(?:match|lookaround)\b).)*\bmatch\b

匹配lookaround actually matches characters, but then gives up the match

第二(没有)

代码语言:javascript
复制
lookaround(?:(?!(?:match|lookaround)).)*match

匹配lookaround actually match

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56415304

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档