regex implementation to replace group with its lowercase version

前端 未结 6 1243
南方客
南方客 2020-12-14 14:03

Is there any implementation of regex that allow to replace group in regex with lowercase version of it?

6条回答
  •  执笔经年
    2020-12-14 14:35

    If you're using an editor like SublimeText or TextMate1, there's a good chance you may use

    \L$1
    

    as your replacement, where $1 refers to something from the regular expression that you put parentheses around. For example2, here's something I used to downcase field names in some SQL, getting everything to the right of the 'as' at the end of any given line. First the "find" regular expression:

    (as|AS) ([A-Za-z_]+)\s*,$
    

    and then the replacement expression:

    $1 '\L$2',
    

    If you use Vim (or presumably gvim), then you'll want to use \L\1 instead of \L$1, but there's another wrinkle that you'll need to be aware of: Vim reverses the syntax between literal parenthesis characters and escaped parenthesis characters. So to designate a part of the regular expression to be included in the replacement ("captured"), you'll use \( at the beginning and \) at the end. Think of \ as—instead of escaping a special character to make it a literal—marking the beginning of a special character (as with \s, \w, \b and so forth). So it may seem odd if you're not used to it, but it is actually perfectly logical if you think of it in the Vim way.


    1 I've tested this in both TextMate and SublimeText and it works as-is, but some editors use \1 instead of $1. Try both and see which your editor uses.

    2 I just pulled this regex out of my history. I always tweak regexen while using them, and I can't promise this the final version, so I'm not suggesting it's fit for the purpose described, and especially not with SQL formatted differently from the SQL I was working on, just that it's a specific example of downcasing in regular expressions. YMMV. UAYOR.

提交回复
热议问题