正则表达式在bash前pression [英] regex in bash expression

查看:156
本文介绍了正则表达式在bash前pression的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对在bash前pression正则表达式2的问题。结果

I have 2 questions about regex in bash expression.

1.non贪婪模式<​​/ P>

1.non-greedy mode

local temp_input='"a1b", "d" , "45"'
if [[ $temp_input =~ \".*?\" ]]
then
    echo ${BASH_REMATCH[0]}
fi

的结果是

"a1b", "d" , "45"

在Java的

String str = "\"a1b\", \"d\" , \"45\"";
Matcher m = Pattern.compile("\".*?\"").matcher(str);
while (m.find()) {
    System.out.println(m.group());
}

我可以得到下面的结果。

I can get the result below.

"a1b"
"d"
"45"

但我怎么可以使用非贪婪模式在bash?结果
我可以理解为什么\\[^ \\]的 \\的作品。结果
但我不明白为什么用\\。
的?\\不工作。

2.global匹配结果。

2.global matches

local temp_input='abcba'
if [[ $temp_input =~ b ]]
then
    #I wanna echo 2 b here. 
    #How can I set the global flag?
fi

如何能得到所有的比赛?结果
PS:我只想用正则表达式

How can I get all the matches?
ps:I only wanna use regex.

对于第二个问题,遗憾的混乱。结果
我想呼应b和B,不能算B。

For the second question, sorry for the confusing.
I want to echo "b" and "b", not count "b".

帮助!

推荐答案

有关你的第一个问题,另一种是这样的:

For your first question, an alternative is this:

[[ $temp_input =~ \"[^\"]*\" ]]

有关你的第二个问题,你可以这样做:

For your second question, you can do this:

temp_input=abcba
t=${temp_input//b}
echo "$(( (${#temp_input} - ${#t}) / 1 )) b"

或者为了方便把它放在一个函数:

Or for convenience place it on a function:

function count_matches {
    local -i c1=${#1} c2=${#2}
    if [[ c2 -gt 0 && c1 -ge c2 ]]; then
        local t=${1//"$2"}
        echo "$(( (c1 - ${#t}) / c2 )) $2"
    else
        echo "0 $2"
    fi
}

count_matches abcba b

两者产生输出:

2 b

更新:

如果你想看到比赛你可以使用这样的函数。您也可以尝试其他常规前pressions不仅仅是文字。

If you want to see the matches you can use a function like this. You can also try other regular expressions not just literals.

function find_matches {
    MATCHES=() 
    local STR=$1 RE="($2)(.*)"
    while [[ -n $STR && $STR =~ $RE ]]; do
        MATCHES+=("${BASH_REMATCH[1]}")
        STR=${BASH_REMATCH[2]}
    done
}

例如:

> find_matches abcba b
> echo "${MATCHES[@]}"
b b

> find_matches abcbaaccbad 'a.'
> echo "${MATCHES[@]}"
ab aa ad

这篇关于正则表达式在bash前pression的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆