如何在引号之间匹配字符串中的精确字符串

2024-04-24 08:24:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个变量,它包含例如['Cars', 'House', 'Bike']。我希望能够搜索与字符串中包含的值的精确匹配。你知道吗


例如:

  • 我检查变量中是否存在字符串Cars。它应该返回true。你知道吗
  • 我检查变量中是否存在字符串Car。它应该返回false。你知道吗

我尝试的是:

#!/bin/bash
search="Car"
arr="['Cars', 'House', 'Bike']"
if [[ $search =~ .*"$arr".* ]]; then
    echo "true"
else
    echo "false"
fi
# Output true | Expected false

另一个脚本:

#!/bin/bash
search="Cars"
arr="['Cars', 'House', 'Bike']"
check=0
grep -o "'[^']*'" <<<"$arr" | sed "s/'//g" |
while read -r elem; do
    if [ "$search" == "$elem" ]; then
         check=1
    fi
done
if [ "$check" == 1 ]; then
    echo "true"
else
    echo "false"
fi
# Output false | Expected true

Tags: 字符串echofalsetruesearchifbincheck
3条回答

在本文的第一个Bash示例代码中,正则表达式匹配有几个问题。最大的问题是$search$arr位于匹配运算符的错误一侧。模式中缺少单引号也是一个严重的问题。不管怎样,正则表达式匹配对于这一点来说是过分的。简单的“glob”模式匹配就足够了。试试这个:

#!/bin/bash

search=Car
arr="['Cars', 'House', 'Bike']"

if [[ $arr == *"'$search'"* ]]; then
    echo true
else
    echo false
fi

有关glob模式的信息,请参见glob - Greg's Wiki。你知道吗

正如其他人所说,在bash中使用^{}解析JSON。你知道吗

如果你真的不想这样,你可以尝试以下任何一种:

search="'Car'" # add the single quotes to the search string
# or
search="\bCar\b" # \b is regex syntax for word boundary, meaning the word begins/ends there

在Python中:

search="Car"
arr="['Cars', 'House', 'Bike']"

import ast
output = search in ast.literal_eval(arr)

作为shell脚本中输出TrueFalse的一行:

python -c 'import sys; import ast; print(sys.argv[1] in ast.literal_eval(sys.argv[2]))' "$search" "$arr"

作为shell脚本中返回0(正常)或-1(不正常)退出状态的一行程序,在shell中通常是这样:

python -c 'import sys; import ast; sys.exit(0 if sys.argv[1] in ast.literal_eval(sys.argv[2]) else -1)' "$search" "$arr"

相关问题 更多 >