我有这样一句话:
"The dog jumped over the moon because he likes jumping"
我想找到所有匹配的单词jump.*
,即jumped
和jumping
。我怎样才能做到这一点?
目前我有一个变量中的句子,$sentence
. 而且我知道我想测试的匹配词,例如$test
is jump
。
谢谢
如果您想纯粹在 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
试试这个正则表达式:
/\bjump.*?\b/
见这里。\b
匹配单词边界以及以 .jump.*?
开头的所有内容jump
。
在 bash 中,您可以将其与 grep 一起使用:
echo $sentence | grep -oP "\b$test.*?\b"
echo $sentence | tr ' ' '\n' | grep "^$test"
更彻底:
echo $sentence | tr '[[:space:]]' '\n' | grep "^$test"
http://www.linuxjournal.com/content/bash-regular-expressions
看起来它可能会帮助你。(我不擅长正则表达式或 bash,抱歉)