Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern matching digits does not work in egrep?

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 

?

like image 948
user377622 Avatar asked Jul 06 '10 10:07

user377622


People also ask

Why is regex not working?

You regex doesn't work, because you're matching the beginning of the line, followed by one or more word-characters (doesn't matter if you use the non-capturing group (?:…) here or not), followed by any characters.

Which command can be used for pattern matching?

Pattern matching is used by the shell commands such as the ls command, whereas regular expressions are used to search for strings of text in a file by using commands, such as the grep command.


2 Answers

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

  • egrep mini tutorial

References

  • regular-expressions.info/Flavor comparison
    • Flavor note for GNU grep, ed, sed, egrep, awk, emacs
      • Lists the differences between grep vs egrep vs other regex flavors
like image 81
polygenelubricants Avatar answered Sep 20 '22 17:09

polygenelubricants


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 
like image 35
André Laszlo Avatar answered Sep 19 '22 17:09

André Laszlo