Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex grep:尝试查找回文时返回引用无效_Regex_Bash_Sh_Palindrome - Fatal编程技术网

Regex grep:尝试查找回文时返回引用无效

Regex grep:尝试查找回文时返回引用无效,regex,bash,sh,palindrome,Regex,Bash,Sh,Palindrome,我有一个bash脚本,试图从给定的words.txt文件中识别回文,我认为我使用grep的方法是正确的,但我不确定。我必须仅使用字符类,如\w或[:alpha:://code>来引用字母表中的字母,但每当我尝试执行程序时,就会出现错误: grep:无效的反向引用 有人能解释一下如何解决这个问题吗?谢谢 编辑: 我的新代码,但现在正则表达式3(几乎可以工作,但给了我一个额外的词,它不应该)和5(没有做任何事情)没有做他们应该做的,有什么帮助吗 #!/bin/bash src_file="word

我有一个bash脚本,试图从给定的
words.txt
文件中识别回文,我认为我使用grep的方法是正确的,但我不确定。我必须仅使用字符类,如
\w
[:alpha:://code>来引用字母表中的字母,但每当我尝试执行程序时,就会出现错误:

grep:无效的反向引用

有人能解释一下如何解决这个问题吗?谢谢

编辑: 我的新代码,但现在正则表达式3(几乎可以工作,但给了我一个额外的词,它不应该)和5(没有做任何事情)没有做他们应该做的,有什么帮助吗

#!/bin/bash

src_file="words.txt"

regex1='^(.)(.).\2\1'
regex2='^(.)(.)(.)\3\2\1'
regex3='^(.)(.)(.).\3\2\1'
regex4='(.)\1+'
regex5='^(.)\1{2}'

echo 'These are the five letter palindromes:'
egrep $regex1 $src_file

echo ' '
echo 'These are the six letter palindromes:'
egrep $regex2 $src_file

echo ' '
echo 'These are the seven letter palindromes:'
egrep $regex3 $src_file

echo ' '
echo 'These are the words that contain at least two instances of the same doubled characters (such as willfully (contains ll twice) and riffraff (contains ff twice)):'
egrep $regex4 $src_file

echo ' '
echo 'These are the words that contain at least three instances of doubled characters (such as bookkeeper  (oo, kk, and ee) and keenness (ee, nn, and ss):'
egrep $regex5 $src_file


您的
regex3
看起来几乎没有问题,但可能的过度匹配将发生在 诸如
wow-wow
复兴者
之类的词。那么请尝试:

regex3='^(.)(.)(.)\w\3\2\1$'
严格来说,将所有点替换为
\w
更安全,如下所示:

regex3='^(\w)(\w)(\w)\w\3\2\1$'
毋庸置疑,
regex1
regex2
需要锚定
$

regex4
开始,它应该是:

regex4='(\w)\1.*\1\1'
regex5='(\w)\1.*(\w)\2.*(\w)\3'

任意匹配
riffraff

regex5
应为:

regex4='(\w)\1.*\1\1'
regex5='(\w)\1.*(\w)\2.*(\w)\3'
簿记员
敏锐度
匹配

请注意,字符类
\w
相当于
[[:alnum:]
。 如果要将匹配仅限于字母,请替换
\w
使用
[:alpha:]

顺便说一句,您还可以检查变量
$str
是否是具有以下内容的回文:

[[ $str = $(rev <<< "$str") ]] && echo "$str is a palindrome"

[[$str=$(rev用
grep
替换
egrep
,或删除括号前的所有反斜杠。
egrep$regex3$src_文件
,其中
$regex3
基本上是未定义的,很可能会生成错误消息。祝你好运。@Cyrus欢呼,谢谢你!不过,现在我意识到我的regex是错误的……我完全同意。)ght我有6个字母的回文和()()\3\2\1,但这不起作用,而且它的回文超过6个字母,你知道为什么吗?
regex2='^\(.\)\(.\)\(.\)\(.\)\3\2\1$”
?请参阅: