This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes What ?: does in the regular expression (?:\w*?)? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "What ?: does in the regular expression (?:\w*?)? " Watch "What ?: does in the regular expression (?:\w*?)? " New topic
Author

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

Bruce Jin
Ranch Hand

Joined: Sep 20, 2001
Posts: 666
(?:\w*?)?

What ?: does in the regular expression?

Thanks


BJ - SCJP and SCWCD
We love Java programming. It is contagious, very cool, and lot of fun. - Peter Coad, Java Design

Crazy Bikes created by m-Power
John de Michele
Rancher

Joined: Mar 09, 2009
Posts: 600
Bruce:

Look here.

John.
Bruce Jin
Ranch Hand

Joined: Sep 20, 2001
Posts: 666
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
Sheriff

Joined: Sep 28, 2004
Posts: 18501
    
  40

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


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Bruce Jin
Ranch Hand

Joined: Sep 20, 2001
Posts: 666
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

Joined: Oct 27, 2005
Posts: 19649
    
  18

Just try this with both regular expressions, and see what it returns.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: What ?: does in the regular expression (?:\w*?)?
 
Similar Threads
problem in understandin the code
Why are they called Regular Expressions
Regular Expression issue
regular expression to Remove field inside [ ] brackets
what is the meaning of below regular expression