【问题标题】:Using a regular expression for a choice of a few strings使用正则表达式选择几个字符串
【发布时间】:2016-12-28 04:17:50
【问题描述】:

这是正则表达式'^(v{1,2})?(l|d)?\s+((\bblue\b)|(\bred\b)|(\bgrey\b))'

似乎我无法获得 \s+ 后跟可以进入 \s+ 的单词的格式

我想是否接受以下字符串中的任何内容 'vvlblue, vlblue, lblue, blue, dblue, vdblue, vvdblue, vvlred, vlred .... vdred, vvdred, vvlgrey, vlgrey ... vdgrey, vvdgrey)

如果我输入

lblue
lred
dred

运行时进入标准输入我希望它打印

C - Colours: lblue
C - Colours: lblue, lred
C - Colours: lblue, lred, dred

.

来自这段代码

read -p ""
while [ $REPLY != "n" ]
do
        #^(v{1,2})?(l|d)?
        if [[ $REPLY =~ '^(v{1,2})?(l|d)?\s+((\bblue\b)|(\bred\b)|(\bgrey\b))' ]]
        then
                colours+=($REPLY)
                echo "C - Colours: "
                printf '%s,' "$colours[-]"
                printf "\n"
        else
                printf "Invalid colour\n"
        fi
        read -p ""
done

即使我将这条线剥离到只是

if [[ $REPLY =~ '^\s+(blue)' ]]

或者我把它改成

if [[ $REPLY =~ '^\s+(\bblue\b)' ]]

然后输入蓝色这个词,我仍然得到“无效颜色”作为输出

【问题讨论】:

  • 明确说明您的要求。您正在尝试做什么以及最小的可验证输入和预期输出。
  • @Inian 现在好点了吗?我对其进行了编辑,使其具有应该打印的确切输出。

标签: regex bash command-line


【解决方案1】:

这是在正则表达式和输出中进行了一些修改的代码:

colours=()
read -p ""
while [ $REPLY != "n" ]
        do

        if [[ $REPLY =~ ^(v{,2})(l|d)?(blue|red|grey)$ ]]
        then
                colours+=($REPLY)
                echo -n "C - Colours: "
                printf '%s, ' "${colours[@]}"
                printf "\n"
        else
                printf "Invalid colour\n"
                fi
                read -p ""
        done

【讨论】:

    【解决方案2】:

    您只是在寻找红色蓝色和灰色吗?如果是这样,你为什么不为你的正则表达式做red|blue|grey?但是这里是修改后的版本,字符串正则表达式比较不需要引号。

    while read REPLY
    do
            if [[ "$REPLY" =~ ^(v{1,2})?(l|d)?(blue|red|grey) ]]
            then
                    colours="$colours $REPLY"
                    echo "C - Colours: $colours"
            else
                    printf "Invalid colour\n"
            fi
    done
    

    这是输出:

    lblue
    C - Colours:  lblue
    lred
    C - Colours:  lblue lred
    dred
    C - Colours:  lblue lred dred
    

    希望对你有帮助

    【讨论】:

    • v{1,2})? eq v{,2}
    猜你喜欢
    • 2021-05-16
    • 2019-06-16
    • 1970-01-01
    • 2018-09-19
    • 2022-11-18
    • 2018-07-22
    • 1970-01-01
    • 2013-03-01
    相关资源
    最近更新 更多