24

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?

34

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\@!
| improve this answer | |
  • Perfect. Can you please one liner info on the regex? Would be really helpful. Thanks – mtk Sep 12 '13 at 9:08
  • 1
    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. – Ingo Karkat Sep 12 '13 at 9:42
  • 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). – evilsoup Sep 12 '13 at 12:35
  • Thank's a lot: \d\{4} in Vi it's a trivial one at all – installero Aug 15 '15 at 10:30
10

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.

| improve this answer | |
2

Escaping brackets works: \d\{2\}

| improve this answer | |
1

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

/\<\%(\d\d\d\d\d\)\>
| improve this answer | |
-1

For someone like myself reaching this page simply to look for a pattern matching any length of digits:

\d\+

(It took me some time to figure out the mandatory extra escaping \ before +)

| improve this answer | |
  • + quantifier stands for 1 or more occurrence. This regular expression matches 1 or more occurrences of digits. – gaganso Jul 11 '18 at 18:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.