-3

如何在 shell 脚本中使用正则表达式验证给定的输入字符串是否是有效的十六进制值

例如:

Input var="ff:ff:fe:ff"

有一个:分隔符值

我想将此正则表达式用于任何输入字符串

var = "ff:ff:fe:ff:fe"
var = "ff:ff:fe:ff:fe:fe:ff:ff"
\b0[xX][0-9a-fA-F]+\b



#!/bin/bash -x
var="fe:fe:fe:fe"
regex="/^([0-9A-F]+:?){4}$/"
if [[ $var =~ $regex ]]; then
echo "valid"
fi
4

1 回答 1

4
^([0-9A-Fa-f]{2})(:[0-9A-Fa-f]{2})*$

测试

$ if [[ "ff:af:ff:23:a2:ad" =~ ^([0-9A-Fa-f]{2})(:[0-9A-Fa-f]{2})*$ ]]; then 
   echo "match"; 
  fi 
$ match

$ if [[ "definitlynottherightformat" =~ ^([0-9A-Fa-f]{2})(:[0-9A-Fa-f]{2})*$ ]]; then 
   echo "match"; 
  fi 
$
于 2013-06-07T10:40:36.570 回答