用正则表达式替换Bash变量无法按预期工作 [英] Bash variable substitution with a regex not working as expected

查看:105
本文介绍了用正则表达式替换Bash变量无法按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个包含以下字符串的bash变量:

Given a bash variable holding the following string:

INPUT="Cookie: cf_clearance=foo; __cfduid=bar;"

为什么替换${INPUT/cf_clearance=[^;]*;/}会产生输出:Cookie: 而不是我期望的输出:Cookie: __cfduid=bar;

Why is the substitution ${INPUT/cf_clearance=[^;]*;/} producing the output: Cookie: instead of what I'd expect: Cookie: __cfduid=bar;

在在线正则表达式验证器中测试相同的正则表达式可确认cf_clearance=[^;]*;仅应与cf_clearance=foo;匹配,而不与字符串的其余部分匹配.

Testing the same regex in online regex validators confirms that cf_clearance=[^;]*; should match cf_clearance=foo; only, and not the rest of the string.

我在做什么错了?

推荐答案

使用实际的正则表达式匹配功能代替用于模式的参数扩展.

Use the actual regular-expression matching features instead of parameter expansion, which works with patterns.

[[ $INPUT =~ (.*)(cf_clearance=[^;]*;)(.*) ]]
ans=${BASH_REMATCH[1]}${BASH_REMATCH[3]}

您还可以使用扩展模式,等效于幂中的正则表达式:

You can also use an extended pattern, which is equivalent to a regular expression in power:

shopt -s extglob
$ echo "${INPUT/cf_clearance=*([^;]);/}"

这篇关于用正则表达式替换Bash变量无法按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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