How many times does the Vim editor match a string appear

Source: Internet
Author: User
Tags regular expression

Vim combines regular expressions to achieve complex functions, such as
Common find substitution%s/matching strings/replacement strings in vim/g
If you want to match only the number of strings:
%s/string/&/gn
N, which represents only the number of matches to be reported, without actual substitution.
What if you want only the number of occurrences of this string in the current line?
: s/string/&/gn
If the number of occurrences of a string is found between M and n rows
: m,ns/string/&/gn

If there are no more than 2 BBB per line, this can be done simply:
:%s/(bbb.*) bbb/1/
This command is better understood, under ordinary VI should also be able to use. But because of the greed of the *, when BBB exceeds 2, it will remove the last BBB instead of the second. To avoid this problem, the above command can be rewritten as:
:%s/(bbb.{ -}) bbb/1/
(bbb.*) @<= is a so-called 0-width "assertion" (to be honest, I have always been very sick of translating some of the terms in the regular term), which is popularly said to match not the string but the "position". What kind of position? This is where the front matches the bbb.*, which is where the BBB was previously seen. Note that "those" are used here because there are a lot of positions in the back of the first BBB that match the conditions. Then the second BBB appears in the same position, and naturally the second BBB matches the following expression:
(bbb.*) @<=bbb
Of course the third fourth (if any) also matches, but the first match is the second BBB.
It seems that the quantifiers appearing in the assertion should be careful when discussing its greed.

Vim is really powerful, the regular expression of the grammar expansion is also outside the mainstream of their own system, it is inevitable to us and add some learning costs

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.