Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Now, I have three strings to be matched by a single re -- 'a', 'ab','ac' I suppose one correct re should be 'a[bc]?', but it seems not correct. What is the correct one?

I try it in grep command. And it seems that there is no '?' in grep's regex. So how to do this matching in grep?

Thanks to @anubhava, I now can match all these three strings by:

grep -E 'a[bc]?' <file>

However, this expression also matches 'ad'.

In fact, I want to match all these situation: 'a','abc','ab','ac' but do not want to match 'ad' or 'ae'

share|improve this question
1  
It matches 'ad' because it matches 'a'; did you try using the word boundaries as anubhava suggested? –  Jack Jun 17 '13 at 6:26
    
@EarthWorm: My suggested command was grep -E "\ba[bc]?\b" file (note extra word boundaries). –  anubhava Jun 17 '13 at 14:01
add comment

migrated from stackoverflow.com Jun 19 '13 at 9:36

This question came from our site for professional and enthusiast programmers.

3 Answers

up vote 3 down vote accepted

If you want to use above in a grep command then use extended regex support switch -E with word boundaries:

grep -E "\ba[bc]?\b" file

OR

grep -E "\<a[bc]?\>" file
share|improve this answer
add comment

To use this expression in basic mode, you need to escape the question mark:

grep 'a[bc]\?' file

Update

To address your latest question, I would advice using P(erl) mode:

grep -P 'a(?![de])|a[bc]|abc'

These are the alternations:

  1. Match an 'a' if not followed by 'd' or 'e' (it uses negative look-ahead)

  2. Match 'ab' or 'ac'

  3. Match 'abc'

share|improve this answer
add comment

If you want the string to match the regex from beginning to end, you need to include in the regex the start ^ and end $ markers

^a[bc]?$

If the markers are not part of the regex 123ab456 will match the regex.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.