我有一个bash脚本,我试图从给定的words.txt
文件中识别回文,我认为使用grep的方法正确,但是我不确定。我只需要使用字符类,例如\w
或[:alpha:]
来引用字母表中的字母,但是每当我尝试执行该程序时,我都会遇到错误:
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
或revivers
之类的词。然后请尝试:
regex3='^(.)(.)(.)\w\3\2\1$'
严格地说,用\w
将所有点替换为:
regex3='^(\w)(\w)(\w)\w\3\2\1$'
不用说$
和regex1
需要锚regex2
。
从regex4
开始,应该是:
regex4='(\w)\1.*\1\1'
或
regex4='((\w)\2).*\1'
与willfully
和riffraff
匹配。
并且regex5
应为:
regex5='(\w)\1.*(\w)\2.*(\w)\3'
与bookkeeper
和keenness
匹配。
请注意,字符类别\w
等效于[[:alnum:]]
。如果您想只将匹配限制为字母,请替换\w
用[[:alpha:]]
。
希望这会有所帮助。