在bash中使用正则表达式的意外结果

时间:2019-03-29 12:30:43

标签: regex bash scripting

我尝试制作正则表达式,以验证介于-100到100之间的数字。 我做的正则表达式是^ [-+]?([0-9] [0-9]?| 100)$。 我正在寻找字符串中的模式,而不仅仅是字符串本身。

这是我的脚本:

{
  "ID": "5c9b2de495e8d81ef437539e",
  "WeightingFactor": "BIC",
  "TargetAmount": 1000,
  "FilterCondition": {
    "_cls": "ComplexFilter",
    "Condition": "AND",
    "Rules": [{
        "_cls": "Filter",
        "Category": "MOODYSFOREIGNCURRENCYCEILINGRATING",
        "Operator": "in list",
        "Value": "A1,A2,A3"
      },
      {
        "_cls": "Filter",
        "Category": "ASOFDATE",
        "Operator": "less or equal",
        "Value": "26 Nov 2028"
      },
      {
        "_cls": "ComplexFilter",
        "Condition": "OR",
        "Rules": [{
            "_cls": "Filter",
            "Category": "ASOFDATE",
            "Operator": "less or equal",
            "Value": "26 Nov 2028"
          },
          {
            "_cls": "Filter",
            "Category": "ASOFDATE",
            "Operator": "less or equal",
            "Value": "26 Nov 2029"
          }
        ]
      }
    ],
    "Not": false
  }
}

这是我的输入文件:

#!/bin/bash

a="input2.txt"

while read -r line; do
mapfile -t d <<< "$line"

for i in "${d[@]}"; do
  if [[ "$i" =~ ^[-+]?([0-9][0-9]?|100)$ ]]; then
  echo "$i"
  fi
 done
done < "$a"

实际结果什么都没有。

预期结果:

add $s1 $s2 $s3
sub $t0 
sub $t1 $t0 
addi $t1 $t0 75
lw $s1 -23($s2)

2 个答案:

答案 0 :(得分:0)

[...]表示一组字符,其中的破折号可用于指定字符范围。例如,正则表达式中的[4-6u-z]表示字符4,5,6,u,v,w,x,z中的一个。您的表达式[1-200]仅与字符(数字)0、1和2匹配。

因此,在您的情况下,我将分两步进行:首先,从您的字符串中提取初始数字部分,然后对结果进行算术比较。例如(未经测试!):

if [[ $i =~ ^-?[0-9]+ ]]
then
  intval=${BASH_REMATCH[0]}
  if (( intval >= -200 && intval <= 1000 ))
  then
    ....

请参阅bash手册页以获取 BASH_REMATCH 数组的说明。

答案 1 :(得分:0)

#first store your file in an array so that we could pass thru the words
word_array=( $(<filename) )
for i in "${word_array[@]}"
do 
if [[ $i =~ ^([[:blank:]]{0,1}-?[0-9]+)([^[:digit:]]?[^[:blank:]]*)$ ]]
#above line looks for the pattern while separating the number and an optional string 
#that may follow like ($s2) using '()' so that we could access each part using BASH_REMATCH later.
then 
#now we have only the number which could be checked to fall within a range
[ ${BASH_REMATCH[1]} -ge -100 ] && [ ${BASH_REMATCH[1]} -le 100 ] && echo "$i"
fi
done

示例输出

75
-23($s2)

注意:该模式可能需要更多测试,但是您可以吸收这个想法。