我们有很多\foo{something}
。由于花括号内的字符串包含奇数个字符,我们想在字符串后面添加一个空格。结果将是\foo{something }
。我们只想要奇数个字符。例如,在\foo{string}
中,花括号内的字符串具有偶数个字符,那么我们不会添加空格。
我尝试过:
[..]*.
表示1,3,5 ......字符。\foo{[..]*.}
将是我的匹配序列。:%s/\foo{[..]*.}/\foo{[..]*. }/g
将添加我们想要的空间。但我们失败了。
答案 0 :(得分:2)
这个cmd应该这样做:
:%s/\\foo{\zs[^}]\+\ze}/\=substitute(submatch(0), '$', len(submatch(0))%2?' ':'','g')/
答案 1 :(得分:1)
:%s/\\\w\+{\([^}]\{2}\)*[^}]\zs\ze}/ /g
说明:
在宏\([^}]\{2}\)*
之间查找字符对([^}]
),后跟另一个字符(\\\w\+{...}
)。然后做一个替换,增加一个额外的空间。
细节的荣耀:
\\\w\+{...}
找到模式\foo{...}
[^}]
}
,\([^}]\{2}\)*
\([^}]\{2}\)*[^}]
\zs
和\ze
设置匹配开始和结束的位置更多帮助请看:
:h :s
:h :range
:h /\[]
:h /\(
:h /\zs
:h /\w
:h /star
:h /\+
答案 2 :(得分:0)
这应该有效
:%s/\v[(\{(\w{2})*) ]@<!}/ }/g
分解:
%s " run substitute on every line
\v " very magic mode
[(\{(\w{2})*) ] " matches every `{` followed by an equal number of word
characters and space, since you don't want to add a space again everytime
you run it.
@<!} " negative lookahead, matches all } not following the pattern before
<强>更新强>
要解决您在注释中阅读的精确问题,以下命令会有所帮助。
g/^\\foo/s/\v(\{([^}]{2})*)@<!}/ }/g
的变化:
g/^\\foo/... " only run it on lines starting with \foo
[^}] " it does now match all characters between { and } not only word
characters.
陷阱:在线上多个大括号(\foo{"hello{}"}
和\foo{string} {here it would also match}
f.e.将失败)不能正常工作。如果其中一个是问题。告诉我