如何将捕获的组放入一个字符类中来否定它?

时间:2015-02-04 19:37:06

标签: regex

我正在尝试解析我的扑克手牌历史,以确定我在比赛中打出7-2的牌数(也就是说,7是一个套牌,而2是另一套牌)。

我可以在77或22场比赛中获胜。

$ grep -E "Dealt to .* \[([7|2])[s|c|h|d]\s\1" ~/poker/handhistory/*/* | wc -l
  15

我在那场比赛中打了72场同样的牌。

$ grep -E "Dealt to .* \[([7|2])([s|c|h|d])\s[7|2]\2" ~/poker/handhistory/GMulligan/* | wc -l
   9

我已经获得了第一张牌的排名。我想做的是有一个字符类,如果第一个捕获组是2则包含[7],如果第一个捕获组是7,则包含[2]。

有人可以帮忙吗?

更新: 对不起,一些示例数据显然会对此有所帮助

player1参与的每一手牌都有这样一条线:

Dealt to player1 [4c Ac]

我正在寻找“[”和“]”

中的所有以下内容

7h 2c 7h 2d 7小时2秒 7c 2h 7c 2d 7c 2s 7d 2h 7d 2c 7d 2s 7s 2h 7s 2c 7s 2d

1 个答案:

答案 0 :(得分:1)

您可以使用否定前瞻来实现您想要做的事情。

https://regex101.com/r/yK4oC7/2(*表示匹配)

Dealt to player1 []
Dealt to player1 [7c 2c]
Dealt to player1 [7c 2h] *
Dealt to player1 [7d 7c]

以下是正则表达式的细分\[([72])([sdch]) (?\!\1)([72])(?\!\2)([sdch])(在bash中,!是一个特殊字符,必须要转义。因此,当mamy语言使用(?!....)执行负向前瞻时,bash似乎需要(?\!....)

\[             - match literal [
([72])         - match 7 or 2 and capter as \1
([sdch])       - match s,d,c or h
 (?!\1)([72])  - match a space followed by digit that's not the same as \1 
                 and is 7 or 2
(?!\2)([sdch]) - match sdch where it's not the same as whichever of the
                 four was matched as \1

编辑:我不使用bash,所以我不熟悉细微差别,但How to use regex negative lookahead的两个答案在设计正确的语法时应该是有用的。