简体   繁体   English

创建一个正则表达式,以查找用逗号分隔的字符串,而无需重复中间部分

[英]Create a regex for finding comma-separated strings without repeating the central part

I'm looking for a regex that matches ALL OF and ONLY the following strings boo , foo , tar , boo,foo , boo,tar , foo,tar , foo,boo , tar,boo , tar,foo , boo,foo,tar , boo,tar,foo , tar,boo,foo , tar,foo,boo , foo,boo,tar and foo,tar,boo . 我正在寻找一个正则表达式,它匹配所有OF,并且仅匹配以下字符串boofootarboo,fooboo,tarfoo,tarfoo,bootar,bootar,fooboo,foo,tarboo,tar,footar,boo,footar,foo,boofoo,boo,tarfoo,tar,boo

(Strings that repeat themselves such as boo,boo or boo,boo,tar are NOT GOOD) (重复出现的字符串,例如boo,booboo,boo,tar都不好)

Plus: I need the Regular Expression itself to contain the strings boo , foo and tar only once each. 另外:我需要正则表达式本身仅包含一次字符串boofootar

So, to recap: I want no repetition both in the matched strings and the regEx itself. 因此,回顾一下:我不希望匹配的字符串和regEx本身都重复。

Any way to achieve this result? 有什么办法可以达到这个结果?

this is what I have so far (boo|foo|tar)((,)(boo|foo|tar))* 这是我到目前为止所拥有的(boo|foo|tar)((,)(boo|foo|tar))*

Try this regex: 试试这个正则表达式:

^(boo|foo|tar)(?!.*\1)(?:,(boo|foo|tar)(?!.*\2))*$

Click for Demo 点击演示

Explanation: 说明:

  • ^ - asserts the start of the string ^ -断言字符串的开头
  • (boo|foo|tar) - matches either boo or foo or tar and capture it as group 1 (boo|foo|tar) -匹配boofootar并将其捕获为组1
  • (?!.*\\1) - Negative lookahead to make sure that whatever is stored in group 1 does not come anywhere else later in the string (?!.*\\1) -负向超前以确保存储在组1中的任何内容不会在字符串的后面出现
  • (?:,(boo|foo|tar)(?!.*\\2))*
    • ,(boo|foo|tar) - matches a , followed by either boo or foo or tar and store it as group 2 ,(boo|foo|tar) -与a匹配,后跟boofootar并将其存储为组2
    • (?!.*\\2) - Negative lookahead to make sure that whatever is stored in group 2 does not come anywhere else later in the string (?!.*\\2) -负向超前以确保存储在第2组中的任何内容不会在字符串的后面出现
    • * - matches the above subsequences 0+ times * -匹配上述子序列0次以上
  • $ - asserts the end of the string $ -断言字符串的结尾

Alternative Regex: 替代正则表达式:

^(?:,?(boo|foo|tar)(?!.*\\1))*$

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM