使用bash计算字符串中子字符串的出现次数(count no of occurences of a substring in a string using bash)
计数为2时,模式在字符串中出现三次
echo "axxxaaxx" | grep -o "xx" | wc -l echo "axxxaaxx" | grep -o "xx"It is giving count as 2 where as pattern occurred thrice in the string
echo "axxxaaxx" | grep -o "xx" | wc -l echo "axxxaaxx" | grep -o "xx"最满意答案
使用-P将启用支持外观的 PCRE:
echo "axxxaaxx" | grep -P '(?<=x)x'在这种情况下,我们使用lookbehind,这意味着我们将匹配在它之前有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 matchUsing -P will enable PCRE which supports lookarounds:
echo "axxxaaxx" | grep -P '(?<=x)x'In this case we are using a lookbehind which means that we will match an x which have an x before it. This makes us able to have overlapping matches:
How the regex is "evaluated":
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更多推荐
发布评论