Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

What ?: does in the regular expression (?:\w*?)?

 
Bruce Jin
Ranch Hand
Posts: 672
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
(?:\w*?)?

What ?: does in the regular expression?

Thanks

 
John de Michele
Rancher
Posts: 600
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Bruce:

Look here.

John.
 
Bruce Jin
Ranch Hand
Posts: 672
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks John for the link.

It says:

Special constructs (non-capturing)
(?:X) X, as a non-capturing group

What does this mean?

What is "a non-capturing group" and what is "a capturing group"?

Thanks

 
Henry Wong
author
Marshal
Pie
Posts: 21385
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Bruce Jin wrote:
What does this mean?

What is "a non-capturing group" and what is "a capturing group"?


A group is, by default, capturing -- meaning you can fetch groups (sub-matches inside parens) with the group(int) method.

A non-capturing group is just that -- don't capture the submatch. The group(int) method doesn't return submatches from non-capturing groups. Generally, if you don't need the value of a submatch, the group should be non-capturing, as there is no reason for the regex engine to collect the data for you, if you don't intend to use it.

Henry
 
Bruce Jin
Ranch Hand
Posts: 672
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Henry for the explanation.
It appears that we should use ?: more often.

Is there a simple example that can show the difference between (?:\w*)? and (\w*)?

Thanks
 
Rob Spoor
Sheriff
Pie
Posts: 20606
60
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just try this with both regular expressions, and see what it returns.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic