Regex 正则表达式用已知的第一个和最后一个字替换子字符串

Regex 正则表达式用已知的第一个和最后一个字替换子字符串,regex,bash,Regex,Bash,我有一个字符串说“xyz遛狗abc”。我想删除子字符串“遛狗”,只需要“xyz abc”。如何在bash regex中执行此操作?您可以使用数组: string="xyz walked his dog abc" a=( $string ) result="${a[0]} ${a[-1]}" 您可以使用数组: string="xyz walked his dog abc" a=( $string ) result="${a[0]} ${a[-1]}" 最简单的方法可能是使用sed:se

我有一个字符串说“xyz遛狗abc”。我想删除子字符串
“遛狗”
,只需要
“xyz abc”
。如何在bash regex中执行此操作?

您可以使用数组:

string="xyz walked his dog abc"

a=( $string )

result="${a[0]} ${a[-1]}"

您可以使用数组:

string="xyz walked his dog abc"

a=( $string )

result="${a[0]} ${a[-1]}"

最简单的方法可能是使用
sed
sed-r's/遛狗/”
(用空字符串替换子字符串)。或者使用内置的替换机制(尽管不支持正则表达式):
a=“xyz遛狗abc”;echo“${a/遛狗/}”
最简单的方法可能是使用
sed
sed-r的/遛狗/”
(用空字符串替换子字符串)。或者使用内置的替换机制(尽管不支持正则表达式):
a=“xyz遛狗abc”;echo“${a/遛狗/}”

纯bash:

var="xyz walked his dog abc"
echo ${var/walked*dog/}
xyz  abc
纯bash:

var="xyz walked his dog abc"
echo ${var/walked*dog/}
xyz  abc

虽然正则表达式对于这个特定的操作来说是多余的(我建议),但如果需要更改,最好了解语法:

# Two capture groups, one preceding the string to remove, the other following it
regex='(.*)walked his dog(.*)'
[[ $string =~ $regex ]]
# Elements 1 through n of BASH_REMATCH correspond to the 1st through nth capture
# groups. (Element 0 is the string matched by the entire regex)
string="${BASH_REMATCH[1]}${BASH_REMATCH[2]}"

虽然正则表达式对于这个特定的操作来说是多余的(我建议),但如果需要更改,最好了解语法:

# Two capture groups, one preceding the string to remove, the other following it
regex='(.*)walked his dog(.*)'
[[ $string =~ $regex ]]
# Elements 1 through n of BASH_REMATCH correspond to the 1st through nth capture
# groups. (Element 0 is the string matched by the entire regex)
string="${BASH_REMATCH[1]}${BASH_REMATCH[2]}"

我意识到我把这个问题框错了。走之前的字数不得而知。waled和dog之间的字数未知。dog后面的单词数未知。我们只知道子串以walk开头,以dog结尾。我意识到我把这个问题框错了。walk之前的单词数不详。waled和dog之间的字数未知。dog后面的单词数未知。我们只知道子串以walked开头,以dog结尾。