3

我有这样一句话:

"The dog jumped over the moon because he likes jumping"

我想找到所有匹配的单词jump.*,即jumpedjumping。我怎样才能做到这一点?

目前我有一个变量中的句子,$sentence. 而且我知道我想测试的匹配词,例如$testis jump

谢谢

4

4 回答 4

4

无管道 Bash 解决方案

如果您想纯粹在 Bash 中执行此操作,您可以使用正则表达式匹配运算符和内置的BASH_REMATCH变量来保存结果。例如:

re='\bjump[[:alpha:]]*\b'
string="The dog jumped over the moon because he likes jumping"
for word in $string; do
    [[ "$word" =~ $re ]] && echo "${BASH_REMATCH}"
done

给定您的语料库,这将正确返回以下结果:

jumped
jumping
于 2012-07-10T19:06:10.563 回答
3

试试这个正则表达式:

/\bjump.*?\b/

这里\b匹配单词边界以及以 .jump.*?开头的所有内容jump

在 bash 中,您可以将其与 grep 一起使用:

echo $sentence | grep -oP "\b$test.*?\b"
于 2012-07-10T18:53:06.017 回答
2
echo $sentence | tr ' ' '\n' | grep "^$test"

更彻底:

echo $sentence | tr '[[:space:]]' '\n' | grep "^$test"
于 2012-07-10T18:53:21.460 回答
1

http://www.linuxjournal.com/content/bash-regular-expressions

看起来它可能会帮助你。(我不擅长正则表达式或 bash,抱歉)

于 2012-07-10T18:52:10.257 回答