In the Pattern class it says there are two types of regex: capturing and non-capturing, but I don't understand the difference.
http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html#special
How are they different? When do I have to use each one? Any examples?
Consider a pattern where you need to check for a variety of things in a single position, e.g a bunch of different two character patterns. Normally you use the | alternation operator:
/(ab|cd|ef)/
which requires use of () brackets as well. But those brackets also act as a capturing group. Maybe you really don't want to capture those char sequences, just check for their presence, which is where the non-capturing groups come into play:
/(?:ab|cd|ef)/
You may want to group expressions independently of them capturing something. For instance:
abc(foo|bar)def
If you want to match either "abdfoodef" or "abcbardef", but no other variations, this is the simplest expression. You had to use () to group two expressions to use the |. But this also means that (foo|bar) is the first capturing group.
If you don't want or need the capture, write it as a non-capturing group:
abc(?:foo|bar)def
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With