aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Using quantifiers + - and ? help Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Using quantifiers + - and ? help" Watch "Using quantifiers + - and ? help" New topic
Author

Using quantifiers + - and ? help

Tahir Akram
Ranch Hand

Joined: Jul 03, 2007
Posts: 37
I am unable to understand the use of + quantifier.

How it is used to identify one occurrence. And how * and ? are used.

Any help would be appreciated.



Tahir Akram
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4363
    
    8

It works like this:

a matches a single 'a'
a? matches 0 or 1 'a's
a* matches 0 or more 'a's
a+ matches 1 or more 'a's
Sahil Kapoor
Ranch Hand

Joined: Sep 12, 2009
Posts: 316
@Tahir Akram

\d metacharacter essentially means :
[0-9] ie one out of the digits from 0 to 9.

\d+ metacharacter with + quantifer means :
1 or more number of digits. For example, 1, 12, 43, 12432, and so on so forth


String to match : "a1 aAA 4b"
Index : 012345678

Clearly , first match is 1 at index 1
and second match is 4 at index 7


Suppose

String to match : "1134aAA44bc"

Then , first match is at index 0 and token matched is 1134
Second match is at index 7 and token matched is 44.

Hope it clears !!!
Thanks !!!


SCJP 6.0 96%

(Connecting the Dots ....)
Tahir Akram
Ranch Hand

Joined: Jul 03, 2007
Posts: 37
Thanks Sahil for your concept.



prints 0 , 7 ,

but again unable to understand why \d? prints all indexes?

Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4363
    
    8

Tahir Akram wrote:
but again unable to understand why \d? prints all indexes?

That's because ? means 0 or 1. And it can match zero digits starting from any point you want. You've got to be careful with this using either the ? or * quantifiers.

If you printed out what it was matching at each position alongside the index, you'd get:

0 - '1'
1 - '1'
2 - '3'
3 - '4'
4 - ''
5 - ''
6 - ''
7 - '4'
8 - '4'
9 - ''
10 - ''
11 - '' (because it can also match zero digits starting at the end of the string)
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4363
    
    8

Similarly, using \d*, it would match:

0 - '1134'
4 - ''
5 - ''
6 - ''
7 - '44'
9 - ''
10 - ''
11 - ''
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Using quantifiers + - and ? help