正则表达式匹配包含子集的整个字符串

问题描述 投票:1回答:3

我有很好的正则表达式,但这是我遇到麻烦的一件事。

我有这个字符串:

foo xxx bar   z

我想匹配WHOLE字符串,只要foo和bar在它上面,无论顺序如何。

到目前为止我有这个,但我需要捕获整个字符串:

(?=foo|bar)[^\s]+
regex regex-lookarounds
3个回答
1
投票

试试这个正则表达式:

^(?=.*\bfoo\b)(?=.*\bbar\b)(.*)$

Click for Demo

说明:

  • ^ - 断言线的起点
  • (?=.*\bfoo\b) - 积极前瞻以确保当前行包含由单词边界包围的单词foo
  • (?=.*\bbar\b) - 积极前瞻以确保当前行包含由单词边界包围的单词bar
  • (.*) - 匹配并捕获任何字符的0次出现,但是换行符。
  • $ - 断言该行的结束。

2
投票

你需要的是这样的:

(.*foo.+bar.*)|(.*bar.+foo.*)

但是:ぁzxswい


编辑:我错过了https://regex101.com/r/3SQhg2/1foo必须作为整个单词出现的观点。这是修复:

对于订单foo - > bar

bar

对于订单栏 - > foo(通过简单地交换前一个中的^.*\bfoo\b.*bar\b.*$ foo

bar

两者结合:

^.*\bbar\b.*foo\b.*$

但是:ぁzxswい


1
投票

我想通了,我想删除它,但也许其他人也会有这个问题,所以我也会在这里发布我的答案。

^.*\bfoo\b.*bar\b.*$|^.*\bbar\b.*foo\b.*$

哪个匹配+捕获:

https://regex101.com/r/3SQhg2/4

^
(                    # let's start capturing
 .*                  # if there's something before the two words
 (?:
  (?=\bfoo\b)\w+     # match the first word
  .*                 # if there's something in the middle of the two words
  (?=\bbar\b)\w+     # match the second word
  |                  # OR let's do everything above but in reverse this time
  (?=\bbar\b)\w+
  .*
  (?=\bfoo\b)\w+
 )
 .*                  # if there's something after the two words
)
$

但不是

foo xxx bar   z

yy bar z foo xxx

aa foobb bar

© www.soinside.com 2019 - 2024. All rights reserved.