[英]Sed capture group
I have a problem with sed
unable to correctly capture the \1
capture group in the below example:我遇到问题sed
无法在以下示例中正确捕获\1
捕获组:
echo '//apple' | sed "s/^\(\/\)\{0,2\}apple\(\/\)\?/\1banana\2/"
------------- --
^ ^
| |__ writing back what it captured
|
|_ this is the capture group that I have problem capturing
I expected the output of: //banana
correctly capturing the //
.我预计 output: //banana
正确捕获//
。 How can I make sed
to correctly the \1
capture group?如何使sed
正确成为\1
捕获组?
You only captured one /
.你只捕获了一个/
。
You need to use你需要使用
echo '//apple' | sed 's/^\(\/\{0,2\}\)apple\(\/\)\?/\1banana\2/' # POSIX BRE
echo '//apple' | sed -E 's~^(/{0,2})apple(/)?~\1banana\2~' # POSIX ERE variant
See the online demo .请参阅在线演示。 The POSIX BRE pattern matches POSIX BRE 模式匹配
^
- start of string ^
- 字符串的开始\(\/\{0,2\}\)
- Group 1: zero, one or two occurrences of a /
char \(\/\{0,2\}\)
- 第 1 组:a /
char 出现零次、一次或两次apple
- a fixed string apple
- 一个固定的字符串\(\/\)\?
- an optional Group 2 matchong a /
char. - 一个可选的 Group 2 matchong a /
char。 Note you do not need to escape capturing parentheses, nor ?
请注意,您不需要转义捕获括号, ?
and {min,max}
quantifiers when using POSIX ERE regex that is enabled with the -E
option.和{min,max}
量词,当使用通过-E
选项启用的 POSIX ERE 正则表达式时。
You need not escape /
chars in the sed command when /
is not used as a regex delimiter char.当/
未用作正则表达式分隔符字符时,您无需在 sed 命令中转义/
字符。
Also, see this regex graph :另外,请参阅此正则表达式图:
With an alternate delimiter and -E
use cleaner and easier to read:使用备用分隔符和-E
使用更清晰且更易于阅读:
echo '//apple' | sed -E 's~^(/{0,2})apple(/{0,2})~\1banana\2~'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.