Win a copy of Kotlin in Action this week in the Kotlin forum!
programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering Languages Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Using quantifiers + - and ? help

Tahir Akram
Ranch Hand
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.

Matthew Brown
Bartender
Posts: 4568
9
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
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 !!!

Tahir Akram
Ranch Hand
Posts: 37

prints 0 , 7 ,

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

Matthew Brown
Bartender
Posts: 4568
9
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
Posts: 4568
9
Similarly, using \d*, it would match:

0 - '1134'
4 - ''
5 - ''
6 - ''
7 - '44'
9 - ''
10 - ''
11 - ''