'regex - Optimize up regular expressions in Ruby [duplicate]

Is it possible to optimize the following ruby regexp?

%r{(.*(?:^|\s))#{pfx}\s+#([\w\-\.:/]+)\s+(.+)}.match(line)
/[^\s]\x40todo/.match(line)
/\x40todo(?!\s+#)/.match(line)
/\x40todo\s+#\s/.match(line)
/[^\s]TODO:?/.match(line)
/TODO(?!:?\s+#)/.match(line)
/TODO:?\s+#\s/.match(line)
%r{([\w\-\.]+)(?::(\d+)(?:(m|h)[a-z]*)?)?(?:/([A-Z]+))?}.match(text)

Actually i suppose that 2 - 6 -> no way to optimize except possibility to use grep check if line need to call this regexp#match ??



Solution 1:[1]

The regexes could be improved, but without knowing what you're matching I can't say how. But there's two general optimizations.

  1. Use Regexp.union to turn them into a single regex.
  2. Use match? instead of match if you just want to know whether it matches. This avoids the overhead of making a MatchData object.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Schwern