vim search numbers containing specific number of digits

50,758

Solution 1

There are different regular expression dialects; some (e.g. Perl's) do not require backslashes in the quantification modifier (\d{2}), some (e.g. sed) require two (\d\{2\}), and in Vim, only the opening curly needs it (\d\{2}). That's the sad state of incompatible regular expression dialects.

Also note that for matching exact numbers, you have to anchor the match so that \d\{2} won't match to digits (12) in 123. This can be done with negative look-behind and look-ahead:

\d\@<!\d\{2}\d\@!

Solution 2

Try the following:

\d\{2}

and you should use \ not /

You can find out more about the regular exression of vim on this site or in vim with :help regular.

Solution 3

Escaping brackets works: \d\{2\}

Solution 4

Search numbers of fixed length say 5

/\d\{5\}

match 12345, 123456

As numbers more than 5 digits contain substring of 5 digits, they will be found too.

word boundary start

\<

word boundary end

\>

Then use below to search numbers of exact 5 digits

/\<\d\{5\}\>

match 12345 but not 123456

Use below to search numbers of 5 or more digits.

/\<\d\{5,\}\>

Use below to search numbers of 5 to 8 digits.

/\<\d\{5,8\}\>

Use below to search numbers of 8 or less digits.

/\<\d\{,8\}\>

Shortcut numbers of 1 or more digits

/\d\+

Solution 5

Not as pretty, but this worked for me for 5 digits in a log file.

/\<\%(\d\d\d\d\d\)\>
Share:
50,758

Related videos on Youtube

ekoeppen
Author by

ekoeppen

Updated on September 18, 2022

Comments

  • ekoeppen
    ekoeppen over 1 year

    I need to find specific length numbers in a big document. I tried to use regex for this. For example, If I need to search for numbers with exactly 2 digits, I use \d\d (i.e. /d twice followed by a space). This works well.

    But for finding 10 digit numbers it's not really feasible to type in \d 10 times.

    Tried \d{2}, says 'E486: Pattern not found: \d{2}'

    Is there any quicker/easier way to achieve this?

  • ekoeppen
    ekoeppen over 10 years
    Perfect. Can you please one liner info on the regex? Would be really helpful. Thanks
  • Ingo Karkat
    Ingo Karkat over 10 years
    For someone struggling with the basic regexp syntax, look-behind/ahead is pretty advanced. I probably cannot describe it better than the built-in :help /\@<! and :help /\@!. Don't worry if you don't immediately understand everything; as I said, this is pretty advanced.
  • evilsoup
    evilsoup over 10 years
    You can also put \v at the beginning of the regex if you wish to avoid having to escape the {, see :help magic for more information (it makes vim regex behave a bit more like perl regex, though there are still differences).
  • installero
    installero almost 9 years
    Thank's a lot: \d\{4} in Vi it's a trivial one at all
  • gaganso
    gaganso almost 6 years
    + quantifier stands for 1 or more occurrence. This regular expression matches 1 or more occurrences of digits.