如何在bash中使用正则表达式运算符=〜匹配重复的字符? [英] How to match repeated characters using regular expression operator =~ in bash?

查看:100
本文介绍了如何在bash中使用正则表达式运算符=〜匹配重复的字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用=〜运算符判断一个字符串是否重复了6次或更多次.

I want to know if a string has repeated letter 6 times or more, using the =~ operator.

a="aaaaaaazxc2"
if [[ $a =~ ([a-z])\1{5,} ]];
then
     echo "repeated characters"
fi

上面的代码不起作用.

推荐答案

BASH正则表达式风格,即 ERE 不支持正则表达式中的反向引用. ksh93zsh对此都支持.

BASH regex flavor i.e. ERE doesn't support backreference in regex. ksh93 and zsh support it though.

作为替代解决方案,您可以使用grep中的扩展正则表达式选项来实现:

As an alternate solution, you can do it using extended regex option in grep:

a="aaaaaaazxc2"
grep -qE '([a-zA-Z])\1{5}' <<< "$a" && echo "repeated characters"

repeated characters


编辑:某些ERE实现支持将反向引用作为扩展.例如,Ubuntu 14.04支持它.参见下面的代码段:


Some ERE implementations support backreference as an extension. For example Ubuntu 14.04 supports it. See snippet below:

$> echo $BASH_VERSION
4.3.11(1)-release

$> a="aaaaaaazxc2"
$> re='([a-z])\1{5}'
$> [[ $a =~ $re ]] && echo "repeated characters"
repeated characters

这篇关于如何在bash中使用正则表达式运算符=〜匹配重复的字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆