正则表达式匹配任何东西,字符串,多个字符串,包括VIM中的换行符非贪婪

时间:2012-02-21 06:10:57

标签: sql regex vim replace uppercase

我想在以下内容中替换小写字符串:

SELECT lower1, lower2, lower3 FROM lower4, lower5 WHERE

我使用vim replace将这个正则表达式替换为大写:

:%s/select\_.*\from\_.*\where/\U&/gic

当有其他选择查询时,正则表达式select\_.*\from\_.*\where不好:

例如,

它选择此查询中的所有内容并影响不能大写的字符串

SELECT lower1, lower2, lower3 FROM lower4, lower5 WHERE lower1=cannot_be_uppercased
UNION all
SELECT lower1, lower2, lower3 FROM lower6, lower7 WHERE lower1=cannot_be_uppercased

1 个答案:

答案 0 :(得分:1)

vim正则表达式中非贪婪模式。不要使用*,而是使用\{-}

我认为正则表达式select\_.\{-}from\_.\{-}where就是你想要的。

以下是一些文档。

:h non-greedy

                            *non-greedy*
If a "-" appears immediately after the "{", then a shortest match
first algorithm is used (see example below).  In particular, "\{-}" is
the same as "*" but uses the shortest match first algorithm.  BUT: A
match that starts earlier is preferred over a shorter match: "a\{-}b"
matches "aaab" in "xaaab".

Example         matches ~
ab\{2,3}c       "abbc" or "abbbc"
a\{5}           "aaaaa"
ab\{2,}c        "abbc", "abbbc", "abbbbc", etc.
ab\{,3}c        "ac", "abc", "abbc" or "abbbc"
a[bc]\{3}d      "abbbd", "abbcd", "acbcd", "acccd", etc.
a\(bc\)\{1,2}d      "abcd" or "abcbcd"
a[bc]\{-}[cd]       "abc" in "abcd"
a[bc]*[cd]      "abcd" in "abcd"

The } may optionally be preceded with a backslash: \{n,m\}.