在bash使用正则表达式在一个字符串多个匹配 [英] Multiple matches in a string using regex in bash
本文介绍了在bash使用正则表达式在一个字符串多个匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
一直在寻找与正则表达式bash的一些更高级的正则表达式的信息,并没有发现它的信息。
Been looking for some more advanced regex info on regex with bash and have not found much information on it.
这里的理念,用一个简单的字符串:
Here's the concept, with a simple string:
myString="DO-BATCH BATCH-DO"
if [[ $myString =~ ([[:alpha:]]*)-([[:alpha:]]*) ]]; then
echo ${BASH_REMATCH[1]} #first perens
echo ${BASH_REMATCH[2]} #second perens
echo ${BASH_REMATCH[0]} #full match
fi
outputs:
BATCH
DO
DO-BATCH
那么细它的第一场比赛(批次DO),但我怎么拉的第二场比赛(DO-批)?我只是一片空白这里找不到bash的正则表达式多的信息。
So fine it does the first match (BATCH-DO) but how do I pull a second match (DO-BATCH)? I'm just drawing a blank here and can not find much info on bash regex.
推荐答案
确定这样一种方式我这样做是为了把它放在一个for循环:
OK so one way I did this is to put it in a for loop:
myString="DO-BATCH BATCH-DO"
for aString in ${myString[@]}; do
if [[ ${aString} =~ ([[:alpha:]]*)-([[:alpha:]]*) ]]; then
echo ${BASH_REMATCH[1]} #first perens
echo ${BASH_REMATCH[2]} #second perens
echo ${BASH_REMATCH[0]} #full match
fi
done
which outputs:
DO
BATCH
DO-BATCH
BATCH
DO
BATCH-DO
这工作,但那种我希望如果可能的话把它拉一切从一个正则表达式。
Which works but I kind of was hoping to pull it all from one regex if possible.
这篇关于在bash使用正则表达式在一个字符串多个匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文