O'Reilly logo

Java 9 Regular Expressions by Anubhava Srivastava

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Avoid unnecessary capturing groups to reduce memory consumption

We come across so many examples of regular expressions on the internet that promote unnecessary capturing groups. If we are not extracting any substring or not using a group in backreferences, then it is better to avoid capturing groups by using one or more of the following ways:

  1. We can use character classes in certain cases. Consider the following capturing group:
      (a|e|i|o|u) 

So, instead of using the preceding regex, we can use the following:

      [aeiou]
  1. We can use a non-capturing group by placing a ?: at the start of the group. Consider the following regex:
      (red|blue|white) 

Instead of the previous regex, we can use the following:

      (?:red|blue|white) 
  1. To write a regex ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required