如何匹配正则表达式的数字 [英] How to match digits in regex

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

问题描述

我想一些行对包含数字的正则表达式匹配。

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

如果我把正则表达式=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

推荐答案

阅读在文件名的开头只发现号正则表达式

\\ D \\ W 不工作在的POSIX定期EX pressions 中,你可以使用 [:数字:] 虽然

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

所以你可以做以下任一:

so you can do either of these:

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

测试:

鉴于此脚本:

#!/bin/bash

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

让我们来运行它:

Let's run it:

$ ./a
AAA (bbb 123) CCC matches AAA \(bbb [[:digit:]]+\) CCC

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

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