简体   繁体   English

Bash正则表达式以匹配具有精确整数范围的子字符串

[英]Bash regex to match substring with exact integer range

I need to match a string $str that contains any of 我需要匹配包含以下任何内容的字符串$str

foo{77..93}

and capture the above substring in a variable. 并在变量中捕获上述子字符串。 So far I've got: 到目前为止,我已经:

str=/random/string/containing/abc-foo78_efg/ # for example
if [[ $str =~ (foo[7-9][0-9]) ]]; then
    id=${BASH_REMATCH[1]}
fi
echo $id # gives foo78

but this also captures ids outside of the target range (eg foo95 ). 但这也会捕获目标范围之外的ID(例如foo95 )。 Is there a way to restrict the regex to an exact integer range? 有没有办法将正则表达式限制为精确的整数范围? (tried foo[77-93] but that doesn't work. (尝试了foo[77-93]但这不起作用。

Thanks 谢谢

If you want to use a regex, you're going to have to make it slightly more complex: 如果要使用正则表达式,则必须使其稍微复杂一些:

if [[ $str =~ foo(7[7-9]|8[0-9]|9[0-3]) ]]; then
    id=${BASH_REMATCH[0]}
fi

Note that I have removed the capture group around the whole pattern and am now using the 0th element of the match array. 请注意,我删除了整个模式周围的捕获组,现在使用match数组的第0个元素。

As an aside, for maximum compatibility with older versions of bash, I would recommend assigning the pattern to a variable and using in the test like this: 顺便说一句,为了最大程度地兼容较早版本的bash,我建议将模式分配给变量并在测试中使用,例如:

re='foo(7[7-9]|8[0-9]|9[0-3])'
if [[ $str =~ $re ]]; then
    id=${BASH_REMATCH[0]}
fi

An alternative to using a regex would be to use an arithmetic context, like this: 使用正则表达式的替代方法是使用算术上下文,如下所示:

if (( "${str#foo}" >= 77 && "${str#foo}" <= 93 )); then
    id=$str
fi

This strips the "foo" part from the start of the variable so that the integer part can be compared numerically. 这将从变量的开头去除“ foo”部分,以便可以对数字部分进行数字比较。

Sure is easy to do with Perl: 当然,使用Perl很容易:

$ echo foo{1..100} | tr ' ' '\n' | perl -lne 'print $_ if m/foo(\d+)/ and $1>=77 and $1<=93'
foo77
foo78
foo79
foo80
foo81
foo82
foo83
foo84
foo85
foo86
foo87
foo88
foo89
foo90
foo91
foo92
foo93

Or awk even: 甚至awk

$ echo foo{1..100} | tr ' ' '\n' | awk -F 'foo' '$2>=77 && $2<=93
 {print}'
foo77
foo78
foo79
foo80
foo81
foo82
foo83
foo84
foo85
foo86
foo87
foo88
foo89
foo90
foo91
foo92
foo93

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM