一行中的双字符奇数(GREP)

时间:2017-08-23 09:47:45

标签: regex linux unix grep

我需要在Unix中使用 grep 编写一个正则表达式,它会找到双字符出现奇数次的行。

例如:

unix AA unixAA unix helpme AA //**true**, because 'AA' occurs 3 times

??red blue pink yellow red pink //**true**, because '??' occurs once

unixA unixAA unix unixAA  unix    //**false**, because 'AA' occurs 2 times

??red blue?? pink?? yellow??  //**false**, because '??' occurs 4 times

感谢您的帮助:)

1 个答案:

答案 0 :(得分:3)

这是非常复杂的正则表达式问题。您将需要gnu grep才能使用 期待解决这个复杂的正则表达式:

^(?:(?!(.)\1).)*((.)\3)((?:(?:(?!\2).)*\2){2})*(?:(?!\2).)*$

grep中使用:

grep -P '^(?:(?!(.)\1).)*((.)\3)((?:(?:(?!\2).)*\2){2})*(?:(?!\2).)*$' file

unix AA unixAA unix helpme AA
??red blue pink yellow red pink

RegEx Demo

RegEx分手:

^                         # Start
(?:(?!(.)\1).)*           # Match 0+ characters that don't repeat at start
((.)\3)                   # Match 2 repeats of same character and capture in group #2
((?:(?:(?!\2).)*\2){2})*  # match 0+ occurrence of some text followed by group #2 
(?:(?!\2).)*              # match anything in the end that doesn't have group #2
$                         # End