开发者

Regular Expressions in Vim

开发者 https://www.devze.com 2023-04-13 03:55 出处:网络
I have been using Vim for a while now, and I\'ve come to realize how powerful it is each time I do so. One thing that I know is that each usage leads me to a whole new learning experience about new co

I have been using Vim for a while now, and I've come to realize how powerful it is each time I do so. One thing that I know is that each usage leads me to a whole new learning experience about new commands that always seem to come in handy once I know them.

One thing I notice coming to SO is that a lot of users answer Vim questions in regexps. Things like this: :s/\(\S\+\)/"\1"开发者_StackOverflow社区/ (supposedly this is an awesome regexp). So I have two questions regarding this.

  • (a) Am I not harnessing the full power of Vim if I don't use regexps? Aren't there commands to do pretty much what any regexp would do?

  • (b) If you do think regexps are worth learning, please point me to reading material ranging from intro to advanced levels. If it helps, I use Vim mostly for writing up TeX files and Python scripts.

Thanks SO community, you rock.


a) In my opinion, if you're not using it and you're happy the way you're working now, leave it at that. Once the time comes and you start needing regular expressions for something you'll learn them. To the extent you need. Most people use them in just that way.

Very few know them to the point where they, let's say go writing their own syntax files or something similar.

b) Vim has its own particular flavour of regular expressions (one of many), but for a start, apart from Vim's help of course, I'd recommend one of the introductory books to Perl. For example, Learning Perl. It has a nice gentle approach so that expressions start making sense (and you don't just learn them as one liners for some particular problem at hand). Beginning Perl (free version !) can be found here.

Advanced books on Regexes are Mastering Regular Expressions, and similar of the series. Also, Intermediate and Mastering Perl are not bad.


Essentially Regular expressions are most useful for search and replaces. Many problems can be solved by searching for the offending text and replacing it in a clever manner with desired text. That is not always the best way to solve and rarely is it the only way. Regular expressions find a pattern so if you are wanting to edit text in a bunch of places that has a similar pattern you can often identify them with a regular expression Ex:

/my name is .*

Will find "my name is " "my name is Joe" or anything else that starts with "my name is "
the . matches any character and the * tells vim to match 0 to infinity of the previous symbol (in this case . or anything)
this is probably the simplest form of regex. for more advanced usage use the answers provided by Idigas

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号