aspose file tools*
The moose likes Beginning Java and the fly likes Regex Question - Quantifiers' behavior. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Regex Question - Quantifiers Watch "Regex Question - Quantifiers New topic
Author

Regex Question - Quantifiers' behavior.

Chan Ag
Bartender

Joined: Sep 06, 2012
Posts: 1049
    
  15
My Regex code is given below. Could somebody please help me understand the output ( specifically the highlighted parts of the output). If my string to be matched is only 3 characters long, how can I have a blank string starting at position 3? Would I see this behavior only when the quantifier is a '0 or' more quantifier? Also when I have a pattern that constitutes a zero or more quantifier plus the reluctant behavior, I only get blank strings while my original string is "abc" ( not three blanks or four?). Thanks for your help.



My output listing is as follows.

run:

------------------------------------------

Pattern is [\d]
0 String = 1
1 String = 2
2 String = 3

------------------------------------------

Pattern is [\d]+
0 String = 123

------------------------------------------

Pattern is [\d]+?
0 String = 1
1 String = 2
2 String = 3

------------------------------------------

Pattern is [\d]*
0 String = 123
3 String =

------------------------------------------

Pattern is [\d]*?
0 String =
1 String =
2 String =

3 String =

------------------------------------------

Pattern is [\d]?
0 String = 1
1 String = 2
2 String = 3
3 String =

------------------------------------------

Pattern is [\d]??
0 String =
1 String =
2 String =

3 String =
BUILD SUCCESSFUL (total time: 0 seconds)
Tony Docherty
Bartender

Joined: Aug 07, 2007
Posts: 2366
    
  50
Pattern is [\d]*
0 String = 123
3 String =

* matches 0 or more times in a greedy fashion, so it matches all the digits and no digits at the end of the string.

Pattern is [\d]*?
0 String =
1 String =
2 String =
3 String =

*? matches 0 or more times in a lazy fashion, so it matches before each digit and no digits at the end of the string.

Pattern is [\d]?
0 String = 1
1 String = 2
2 String = 3
3 String =

? matches 0 or one time in a greedy fashion, so it matches each of the digits and no digits at the end of the string.

Pattern is [\d]??
0 String =
1 String =
2 String =
3 String =

*? matches 0 or one time in a lazy fashion, so it matches before each digit and no digits at the end of the string.
Chan Ag
Bartender

Joined: Sep 06, 2012
Posts: 1049
    
  15
Thanks, Tony.

I didn't know it was an empty string and that in the lazy behavior the match is done before the digit.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Regex Question - Quantifiers' behavior.