gpt4 book ai didi

正则表达式匹配 shell 脚本中数组中的数字

转载 作者:行者123 更新时间:2023-12-04 16:18:04 26 4
gpt4 key购买 nike

我有一个来自 bash 的值数组,我只想检查其中是否有数字。它可以包含 - , +开头或结尾的数字和空格,因为 bash 将其评估为刺痛。
因为每个数字都用 , 表示最后我添加了 (,)到正则表达式。
基本上我想检查元素是否是数字。$val看起来像这些。

[ [ -0.13450142741203308, -0.3073260486125946, -0.15199440717697144, -0.06535257399082184, 0.02075939252972603, 0.03708624839782715, 0.04876817390322685 ] ,[ 0.10357733070850372, 0.048686813563108444, -0.1413831114768982, -0.11497996747493744, -0.08910851925611496, -0.04536910727620125, 0.06921301782131195, 0.02547631226480007 ] ]

这是我的代码,它查看每个值并评估每个值。然而,它似乎没有捕获这些案例。
re='^[[:space:]][+-]?[0-9]+([.][0-9]+)?(,)[[:space:]]$'

for j in ${val[*]}
do
if ! [[ "$j" =~ $re ]] ; then
echo "Error: Not a number: $j"
fi
done
它还需要忽略抛出 [ 的情况或 ]], .
任何想法如何纠正这个?谢谢您的帮助。

最佳答案

$val 很可能是作为字符串出现的。
如果您不需要将每个数字验证为完全合法的数字,您可以使用 shell 逻辑来过滤那些明显不是数字的东西:

val='[ [ -0.13450142741203308, -0.3073260486125946, -0.15199440717697144, -0.06535257399082184, 0.02075939252972603, 0.03708624839782715, 0.04876817390322685 ] ,[ 0.10357733070850372, 0.048686813563108444, -0.1413831114768982, -0.11497996747493744, -0.08910851925611496, -0.04536910727620125, 0.06921301782131195, 0.02547631226480007 ] ]'

for e in $val; do # PURPOSELY no quote to break on spaces
e="${e/,}"
case $e in
''|*[!0-9.\-]*) printf "'%s' is bad\n" "$e" ;;
*) printf "'%s' is good\n" "$e" ;;
esac
done
打印:
'[' is bad
'[' is bad
'-0.13450142741203308' is good
'-0.3073260486125946' is good
'-0.15199440717697144' is good
'-0.06535257399082184' is good
'0.02075939252972603' is good
'0.03708624839782715' is good
'0.04876817390322685' is good
']' is bad
'[' is bad
'0.10357733070850372' is good
'0.048686813563108444' is good
'-0.1413831114768982' is good
'-0.11497996747493744' is good
'-0.08910851925611496' is good
'-0.04536910727620125' is good
'0.06921301782131195' is good
'0.02547631226480007' is good
']' is bad
']' is bad
这是超快的,但会在格式错误的“数字”上失败,例如 123-456
如果确实需要过滤掉格式错误的数字,可以使用 awk :
echo "$val" | awk  -v RS="[^0-9.+-]+" '($0+0==$0)'
# all legit numbers from the string...

关于正则表达式匹配 shell 脚本中数组中的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69916158/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com