寻找 ruby 正则表达式来匹配字符串中的多个单词,这些单词可能按不同的顺序排列



我希望匹配以下内容:xxxxxApplexxxxxOrangexxxxx

我需要一个正则表达式,它将这个字符串与Apple+OrangeOrange+Apple匹配,并且只有在字符串中找到两个单词时才匹配。

更新:我喜欢@lagripe的答案(?=.*?(Apple))(?>.*?(Orange)因为可以在我的程序中轻松使用。我将基于 N 个单词以编程方式生成正则表达式。谢谢

.*(apple.*orange|orange.*apple).*

https://rubular.com/r/kwolGiWLBSkPPF

您可以使用此正则表达式:

(?=.*?(Apple))(?>.*?(Orange))

演示:

这里

为什么原子组用于查找情况的资源:

  • https://www.regular-expressions.info/lookaround.html

  • http://www.rexegg.com/regex-lookarounds.html

  • https://stackoverflow.com/a/2973495/8004593
r = /Apple.*Orange|Orange.*Apple/

'xxApplexxOrangexx'.match?(r)  #=> true
'xxOrangexxApplexx'.match?(r)  #=> true
'xxApplexxApplexx'.match?(r)   #=> false
'xxOrangexxOrangexx'.match?(r) #=> false
'xxApplexx'.match?(r)          #=> false
'xxOrangexx'.match?(r)         #=> false
'xxxx'.match?(r)               #=> false

最新更新