bash 正则表达式计算字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20911172/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 09:09:07  来源:igfitidea点击:

Regex to count characters

regexbash

提问by Atomiklan

I'm trying to verify the number of | in the line of a file. In this example it checks for exactly 5 bars.

我正在尝试验证 | 的数量 在文件的行中。在本例中,它检查正好 5 个柱。

^[\|]{5}$

This verifies 5, but doesn't take into account/ignore other characters.

这会验证 5,但不考虑/忽略其他字符。

Dice|Puppy|Button|Sunny|Music|Extra

What am I missing? Regex always throws me off.

我错过了什么?正则表达式总是让我失望。

回答by Bohemian

Try this regex:

试试这个正则表达式:

^[^|]*(\|[^|]*){4}$

回答by John1024

To count the number of pipes:

计算管道数量:

line='Dice|Puppy|Button|Sunny|Music'
npipes="$(echo "$line" | tr -c -d '|' | wc -c)"

To test that the number of pipes is 5:

要测试管道数是否为 5:

[ "$(echo "$line" | tr -c -d '|' | wc -c)" -eq 5 ] && echo success

In this approach, translate (tr) is used to remove all characters except pipe. (It deletes (-d) the everything but (-c) the pipe character). Then, word count (wc) is used to count the number of bytes (-c). This number can be compared against 5 using a standard bash equality test (-eq).

在这种方法中,translate( tr) 用于删除除管道之外的所有字符。(它删除 ( -d) 除 ( -c) 管道字符之外的所有内容)。然后,使用字数 ( wc) 来计算字节数 ( -c)。可以使用标准 bash 相等性测试 ( -eq)将此数字与 5 进行比较。