为什么Vim替换命令' s/\([a- za -z]\) \([a- za -z]\)/\1\2/g '不能删除行' a- c - d '上的所有空格?

时间:2021-06-27 21:20:34

Suppose that I have a line:
a b c d
When I execute the substitute command :s/\([a-zA-Z]\) \([a-zA-Z]\)/\1\2/g on the line, it only remove two spaces, the result is:
ab cd
Why it doesn't remove all the space?

假设我有一行:当我执行替换命令:s/\([a- za -z]\) \([a- za -z]\)/\1\2/g时,它只删除两个空格,结果是:ab cd为什么不删除所有空格?

2 个解决方案

#1


3  

The result you get is expected because the last \([a-zA-Z]\) is a consuming subpattern.

您得到的结果是预期的,因为最后一个\([a- za -z]\)是一个消费子模式。

Consuming means the text matched with the subpattern is a part of the match. The next match can only start after the preceding match, so, the first [a-zA-Z] will not be able to match b as it is matched during the first iteration.

消费意味着与子模式匹配的文本是匹配的一部分。下一个匹配只能在前一个匹配之后开始,所以第一个[a-zA-Z]将不能匹配b,因为它在第一个迭代中被匹配。

To get abcd, use :s/\([a-zA-Z]\) \([a-zA-Z]\)\@=/\1/g where \(...\)\@= is a "lookahead" construct.

abcd,用途:s / \([a-zA-Z]\)\[a-zA-Z]\ \ @ = / \ 1 / g \(…\)\ @ =是一个“超前”构造。

#2


1  

I would do with the handy \zs \ze:

我将用这个方便的\zs \ze:

s/[a-zA-Z]\zs \ze[a-zA-Z]//g

does the job. And easier to read.

是否工作。和更容易阅读。

The different is, this line matches only space(s), instead of [a-zA-Z]s. So you don't have to do look-around thing or group referencing.

不同的是,这条线只匹配空格,而不是a-zA-Z。所以你不需要四处查看或者组引用。

#1


3  

The result you get is expected because the last \([a-zA-Z]\) is a consuming subpattern.

您得到的结果是预期的,因为最后一个\([a- za -z]\)是一个消费子模式。

Consuming means the text matched with the subpattern is a part of the match. The next match can only start after the preceding match, so, the first [a-zA-Z] will not be able to match b as it is matched during the first iteration.

消费意味着与子模式匹配的文本是匹配的一部分。下一个匹配只能在前一个匹配之后开始,所以第一个[a-zA-Z]将不能匹配b,因为它在第一个迭代中被匹配。

To get abcd, use :s/\([a-zA-Z]\) \([a-zA-Z]\)\@=/\1/g where \(...\)\@= is a "lookahead" construct.

abcd,用途:s / \([a-zA-Z]\)\[a-zA-Z]\ \ @ = / \ 1 / g \(…\)\ @ =是一个“超前”构造。

#2


1  

I would do with the handy \zs \ze:

我将用这个方便的\zs \ze:

s/[a-zA-Z]\zs \ze[a-zA-Z]//g

does the job. And easier to read.

是否工作。和更容易阅读。

The different is, this line matches only space(s), instead of [a-zA-Z]s. So you don't have to do look-around thing or group referencing.

不同的是,这条线只匹配空格,而不是a-zA-Z。所以你不需要四处查看或者组引用。