Pattern matching digits does not work in egrep?

RegexGrepCharacter Class

Regex Problem Overview


Why can't I match the string

"1234567-1234567890"

with the given regular expression

\d{7}-\d{10}

with egrep from the shell like this:

egrep \d{7}-\d{10} file

?

Regex Solutions


Solution 1 - Regex

egrep doesn't recognize \d shorthand for digit character class, so you need to use e.g. [0-9].

Moreover, while it's not absolutely necessary in this case, it's good habit to quote the regex to prevent misinterpretation by the shell. Thus, something like this should work:

egrep '[0-9]{7}-[0-9]{10}' file
See also
References

Solution 2 - Regex

For completeness:

Egrep does in fact have support for character classes. The classes are:

  • [:alnum:]
  • [:alpha:]
  • [:cntrl:]
  • [:digit:]
  • [:graph:]
  • [:lower:]
  • [:print:]
  • [:punct:]
  • [:space:]
  • [:upper:]
  • [:xdigit:]

Example (note the double brackets):

egrep '[[:digit:]]{7}-[[:digit:]]{10}' file

Solution 3 - Regex

you can use \d if you pass grep the "perl regex" option, ex:

grep -P "\d{9}"

Solution 4 - Regex

Use [0-9] instead of \d. egrep doesn't know \d.

Solution 5 - Regex

try this one:

egrep '(\d{7}-\d{10})' file

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser377622View Question on Stackoverflow
Solution 1 - RegexpolygenelubricantsView Answer on Stackoverflow
Solution 2 - RegexAndré LaszloView Answer on Stackoverflow
Solution 3 - RegexrogerdpackView Answer on Stackoverflow
Solution 4 - Regexsepp2kView Answer on Stackoverflow
Solution 5 - RegexNikhil JainView Answer on Stackoverflow