[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: Regex Question



Daniel Burrows wrote:
On Mon, Jul 16, 2007 at 09:43:32AM -0700, Bob McGowan <bob_mcgowan@symantec.com> was heard to say:
Next, grep supports what most would now call a subset of full regular expression syntax. This does not include parenthesis or alternation. So when you put a backslash in front of the pipe symbol, 'grep' simply looks for the literal string 'in|hill', which does not exist in the file. Add it and you'll see it work.

  Actually, grep will treat the pipe as alternation, if it's backslash
escaped:

Interesting, I was not aware of this. So I checked the man page and found this:

---
grep understands three different versions of regular expression syntax: “basic,” “extended,” and “perl.” In GNU grep, there is no difference in available functionality using either of the first two syntaxes. In other implementations, basic regular expressions are less powerful. The following description applies to extended regular expressions; differences for basic regular expressions are summarized afterwards.
---
and:
---
In basic regular expressions the metacharacters ?, +, {, |, (, and ) lose their special meaning; instead use the backslashed versions \?, \+, \{, \|, \(, and \).
---

Just goes to show that reading the man page can often help ;) particularly when portability is an issue.


daniel@alpaca:~$ echo -e 'in the grey morning\nwe climbed the hill.' | grep 'in\|hill'
in the grey morning
we climbed the hill.

  Note that I had to double-escape the pipe: once using single-quotes to
hide it from the shell, and once with a backslash to tell grep it was
special.  I could have written:

    grep in\\\|hill

  but that would have been gross and nasty. :)

  Daniel



--
Bob McGowan

Attachment: smime.p7s
Description: S/MIME Cryptographic Signature


Reply to: