使用bash
回答
使用-P
将使PCRE支持lookarounds:
echo "axxxaaxx" | grep -P '(?<=x)x'
在这种情况下,我们使用的是回顾后,这意味着我们将匹配x
这之前有一个x
。这使我们能够有重叠的匹配:
如何在正则表达式是“评价”:
xxx
^^
|Cursor
Looking for x on this position, since there is nothing this will not match
xxx
^^
|Cursor
Looking for x on this position since it's found we got a match
xxx
^^
|Cursor
Looking for x on this position since it's found we got a match
grep
犯规支持重叠的正则表达式的匹配计数没有一个子字符串的出现次数的字符串中。它消耗匹配的字符。在这种情况下,你可以使用-p
开关使Perl兼容的正则表达式(PCRE),并使用正前方看说法是这样的:
$ echo "axxxaaxx" | grep -oP "x(?=x)"
x
x
x
$ echo "axxxaaxx" | grep -oP "x(?=x)" | wc -l
3
$
regex(?=regex2)
积极向前看断言认定regex2
如下所有regex1
之后。虽然匹配的字符为regex2
它不会消耗字符,因此这就是您获得3个匹配的原因。
x(?=x)
积极向前看断言找到所有x
它后面有x
。
在串xxx
,1 x
比赛,因为它有x
后,第2 x
太和第三x
没有。
更多信息,方便的例子可以发现here
能否请您解释一下什么魔法(= X?)呢? – user2481458
这是http://stackoverflow.com/questions/37050030/no-of-occurences-of-patterns-in-string/37050288#37050288的子部分 – user2481458
- 1. 使用bash
- 2. 使用bash
- 3. 使用bash
- 4. 使用bash
- 5. 使用bash
- 6. 使用bash
- 7. 使用bash
- 8. 使用bash
- 9. 使用bash
- 10. 使用bash
- 11. 从使用bash
- 12. 使用find(bash)
- 13. 使用bash
- 14. 使用bash
- 15. 使用bash
- 16. 使用bash
- 17. 从使用bash
- 18. 使用bash
- 19. 使用bash使用Python
- 20. 使用bash脚本
- 21. 使用bash脚本
- 22. 替代使用bash
- 23. 使用bash脚本
- 24. 如何使用bash
- 25. 如何使用bash
- 26. Bash - 内存使用
- 27. 如何使用bash
- 28. 使用python/bash的
- 29. 排序使用bash
- 30. 使用bash和sed
谢谢。这是有效的这种情况,但我试图实现这一点: 给定一个字符串,返回一个子字符串长度2出现在字符串中的次数和字符串的最后2个字符的次数,所以“ hixxxhi“产生1(我们不会计算结束子字符串)。 last2('hixxhi')→1 last2('xaxxaxaxx')→1 last2('axxxaaxx')→2 – user2481458