Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt about Regex and Quantifiers

 
Nya Iwa
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi!
I need some help!
(code below from Sun´s tutorial)



So I run this code.



My question is: why only in the last string (aabbaba) there´s a match of zero length and others (a, ab, aaba) don´t have??
 
Henry Wong
author
Marshal
Pie
Posts: 20892
75
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My question is: why only in the last string (aabbaba) there´s a match of zero length and others (a, ab, aaba) don´t have??


Take a look at your regex. The last case has a different regex -- that can match a zero length string.

Henry
 
Nya Iwa
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Henry!
Could you explain to me why the last case "can match a zero length string" and the the others can't? I know the regex is different, but why when I try a? I can match a zero length string and when I try aa? I can't match it?

I'm so confused! Why this output?
When I try by myself (on paper) I don't get this output!
The relationship between quantifiers, zero-length string and matcher.find() isn't very clear to me..
I don´t know exactly where I'm doing wrong..

Could you please explain to me step by step following the source code how the third case works?
It would be of a great help!!

 
Henry Wong
author
Marshal
Pie
Posts: 20892
75
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Could you explain to me why the last case "can match a zero length string" and the the others can't? I know the regex is different, but why when I try a? I can match a zero length string and when I try aa? I can't match it?


The "?" means zero or one of the previous character. So....

aa? ... matches a letter "a", followed by zero or one "a"s.... basically, it can match "a" or "aa".

a? ... matches zero or one "a"s.... basically, it can match nothing or "a".

Henry
 
Henry Wong
author
Marshal
Pie
Posts: 20892
75
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When I try by myself (on paper) I don't get this output!
The relationship between quantifiers, zero-length string and matcher.find() isn't very clear to me..
I don´t know exactly where I'm doing wrong..


Well, in order to tell you what you are doing wrong, we need to know what you are doing. Please explain to us what you put on paper...

Henry
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic