Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Regex Question - Quantifiers' behavior.

 
Chan Ag
Rancher
Posts: 1089
14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2989
59
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Rancher
Posts: 1089
14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, Tony.

I didn't know it was an empty string and that in the lazy behavior the match is done before the digit.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic