如何在bash脚本中匹配正则表达式中的数字 [英] How to match digits in regex in bash script

查看:72
本文介绍了如何在bash脚本中匹配正则表达式中的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一些行与包含数字的正则表达式进行匹配.

I'm trying to match some lines against regex that contains digits.

Bash 版本 3.2.25:

Bash version 3.2.25:

#!/bin/bash

s="AAA (bbb 123) CCC"
regex="AAA (bbb d+) CCC"
if [[ $s =~ $regex ]]; then
  echo $s matches $regex
else
  echo $s doesnt match $regex
fi

结果:

AAA (bbb 123) CCC doesnt match AAA (bbb d+) CCC

如果我输入 regex="AAA (bbb .+) CCC" 它可以工作,但它不满足我只匹配数字的要求.

If I put regex="AAA (bbb .+) CCC" it works but it doesn't meet my requirement to match digits only.

为什么 d+ 不匹配 123?

推荐答案

使用标准字符集或符合 POSIX 的符号:

Either use standard character set or POSIX-compliant notation:

[0-9]    
[[:digit:]]    

<小时>

使用正则表达式仅查找文件名开头的数字:

dwPOSIX 正则表达式,你可以使用 [:digit:]

d and w don't work in POSIX regular expressions, you could use [:digit:] though

所以你的表达应该是以下之一:

so your expression should be one of these:

regex="AAA (bbb [0-9]+) CCC"
#                ^^^^^^
regex="AAA (bbb [[:digit:]]+) CCC"
#                ^^^^^^^^^^^^

总的来说,你的脚本可以是这样的:

All together, your script can be like this:

#!/bin/bash

s="AAA (bbb 123) CCC"
regex="AAA (bbb [[:digit:]]+) CCC"
if [[ $s =~ $regex ]]; then
  echo "$s matches $regex"
else
  echo "$s doesn't match $regex"
fi

让我们运行它:

$ ./digits.sh
AAA (bbb 123) CCC matches AAA (bbb [[:digit:]]+) CCC

这篇关于如何在bash脚本中匹配正则表达式中的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆