grep:尝试查找回文时无效的反向引用

问题描述 投票:1回答:1

我有一个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

regex bash sh palindrome
1个回答
0
投票

您的regex3看起来还不错,但是在诸如wow wowrevivers之类的词。然后请尝试:

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'

willfullyriffraff匹配。

并且regex5应为:

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

bookkeeperkeenness匹配。

请注意,字符类别\w等效于[[:alnum:]]。如果您想只将匹配限制为字母,请替换\w[[:alpha:]]

希望这会有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.