0

In this question I answered the regex egrep '^qu[a-z]{1}y$' filename.txt contains {1} which in my opinion is completely redundant.

Is there any case in a popular regex flavor (where {n} means "The preceding item is matched exactly n times.") where adding {1} would change the behavior?


There can be reasons for this like originally (possibly in a copy-pasted code) there was another number that was re replaced with 1 or auto generated code etc., but I am not talking about that.

bolov
  • 58,757
  • 13
  • 108
  • 182
  • In regex systems where braces enclose a repeat count, I don't see `{1}` making a difference to the result, any more than you do. Maybe a comma was omitted — but both `{,1}` and `{1,}` have more convenient shorthand notations: `?` and `+`. – Jonathan Leffler Aug 10 '20 at 02:44
  • 1
    This is in fact covered in the [Stack Overflow `regex` tag info page.](/tags/regex/info) – tripleee Aug 10 '20 at 04:33

1 Answers1

2

No, it should never change the behavior. Any pattern without a quantifier matches exactly once, and the quantifier {1} makes the preceding pattern match exactly once. So it should never make a difference.

Other things that I frequently see that are redundant:

  1. Starting or ending a regexp with .* if it's just being used for testing, rather than for returning or replacing the matched portion. A test will succeed if the regexp can be matched anywhere in the subject string, you don't need to say this explicitly (except that some regexp interfaces implicitly anchor their patterns, e.g. Python's re.match() matches at the beginning, and HTML's pattern attribute has implicit ^ and $ anchors).
  2. Quantifying the last pattern in a regexp with + if it's just being used for testing. If a subject string matches with at least one of the pattern, it will also match with exactly one. (As above, it's not redundant if there's an implicit $ anchor at the end.)
Barmar
  • 596,455
  • 48
  • 393
  • 495