如何将文本与变量中的正则表达式进行比较?

时间:2014-05-29 14:36:06

标签: regex bash

我在input.txt中有以下内容:

EA06\\?\.LFRFLB\\?\..*

我想知道这个模式是否与以下字符串匹配:

EA06.LFRFLB.SHELLO

然后我编码:

MY_STRING="EA06.LFRFLB.SHELLO"
REGEX=$(cat input.txt) # EA06\\?\.LFRFLB\\?\..*

if [[ "${MY_STRING}" =~ "${REGEX}" ]]; then
  echo "FOUND"
else
 echo "NOT FOUND"
fi

if [[ "${MY_STRING}" =~ EA06\\?\.LFRFLB\\?\..* ]]; then
  echo "FOUND"
else
 echo "NOT FOUND"
fi

结果:

NOT FOUND
FOUND

这里出了什么问题?为什么第一个if不正确?解决问题的最佳方法是什么?

1 个答案:

答案 0 :(得分:6)

问题是你引用了二元运算符=~的RHS上的变量,这导致变量替换被视为文本文本而不是正则表达式。你需要说:

if [[ "${MY_STRING}" =~ ${REGEX} ]]; then

从手册中引用:

   An additional binary operator, =~, is available, with the  same  prece‐
   dence  as  ==  and !=.  When it is used, the string to the right of the
   operator is considered  an  extended  regular  expression  and  matched
   accordingly  (as  in  regex(3)).   The  return value is 0 if the string
   matches the pattern, and 1 otherwise.  If  the  regular  expression  is
   syntactically  incorrect,  the conditional expression's return value is
   2.  If the shell option nocasematch is enabled, the match is  performed
   without  regard  to the case of alphabetic characters.  Any part of the
   pattern may be quoted to force it to be  matched  as  a  string.

特别注意最后一行:

  

可以引用模式的任何部分以强制它匹配为字符串。