Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a regex in Emacs for exactly 3 digits?

Tags:

regex

emacs

I want to create a regexp in Emacs that matches exactly 3 digits. For example, I want to match the following:

123 345 789 

But not

1234 12 12 23 

If I use [0-9]+ I match any single string of digits. I thought [0-9]{3} would work, but when tested in re-builder it doesn't match anything.

like image 656
Alex B Avatar asked Sep 16 '08 05:09

Alex B


People also ask

How do you represent digits in regex?

\d (digit) matches any single digit (same as [0-9] ). The uppercase counterpart \D (non-digit) matches any single character that is not a digit (same as [^0-9] ). \s (space) matches any single whitespace (same as [ \t\n\r\f] , blank, tab, newline, carriage-return and form-feed).

How do you restrict length in regex?

The ‹ ^ › and ‹ $ › anchors ensure that the regex matches the entire subject string; otherwise, it could match 10 characters within longer text. The ‹ [A-Z] › character class matches any single uppercase character from A to Z, and the interval quantifier ‹ {1,10} › repeats the character class from 1 to 10 times.

How does regex Match 5 digits?

match(/(\d{5})/g);

Can regex be used for numbers?

Real number regex can be used to validate or exact real numbers from a string.


1 Answers

If you're entering the regex interactively, and want to use {3}, you need to use backslashes to escape the curly braces. If you don't want to match any part of the longer strings of numbers, use \b to match word boundaries around the numbers. This leaves:

\b[0-9]\{3\}\b 

For those wanting more information about \b, see the docs:

matches the empty string, but only at the beginning or end of a word. Thus, \bfoo\b matches any occurrence of foo as a separate word. \bballs?\b matches ball or balls as a separate word. \b matches at the beginning or end of the buffer regardless of what text appears next to it.

If you do want to use this regex from elisp code, as always, you must escape the backslashes one more time. For example:

(highlight-regexp "\\b[0-9]\\{3\\}\\b") 
like image 99
Joe Hildebrand Avatar answered Sep 25 '22 14:09

Joe Hildebrand