tags:

views:

40

answers:

2

I have two quick question with regex with grep.

  1. what does \? mean? I didn't find the explanation for question mark (?)

  2. How can I achieve or? for example, the phone number xxx-xxx-xxxx but the first part could be (xxx)

For example, there might be a digit or not between two letters, such as a1b and ab, how to do that?

Thanks!

+1  A: 

? has special meaning in a regular expression. If you want to match a literal question mark, you need to escape it - \?

If you want to match a string both with an without a particular part, you use the question mark - /^a1?b$/ will match either ab or a1b.

Anon.
In grep it's the other way 'round: `?` matches a question mark and `\?` is the zero-or-one quantifier. Unless you use the `-E` option, that is.
Alan Moore
A: 
grep ".*a1\?b.*" files
siposa
In gnu grep, the `*` character does not need a backslash to function as a quantifier, but `?` does. However, the `.*` at either end is redundant, since grep always returns the whole line in which the match was found.
Alan Moore
You are right, my mistake.
siposa