• Post Reply Bookmark Topic Watch Topic
  • New Topic

Regarding regex and the * and ? Quantifiers  RSS feed

 
Nikhil Pujari
Greenhorn
Posts: 21
C++ Firefox Browser Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello all,

Why does the regex: abc[xyz]*def match the string abcxyzdef when the regex abc[xyz]?def fails to match the same string?

The character class [xyz] means match any one of x or y or z. Then, why does [xyz]* match all three?
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16059
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because * means "zero or more", so abc[xyz]*def means abc followed by zero or more of x, y or z, followed by def.

And ? means "exactly one of", so abx[xyz]?def means abc followed by exactly one of x, y or z, followed by def.

So: abcxyzdef = abc followed by 3 chars which are x, y or z, followed by def => matches the first regex (because 3 is equal to "zero or more"), but does not match the second (because 3 is not equal to "exactly one").
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jesper de Jong wrote:And ? means "exactly one of", so abx[xyz]?def means abc followed by exactly one of x, y or z, followed by def.

Wrong. ? means exactly one or none at all. For abc[xyz]?def there are 4 possible values: abcdef, abcxdef, abcydef and abczdef.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16059
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, my mistake Rob!
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rob Spoor wrote:Wrong. ? means exactly one or none at all. For abc[xyz]?def there are 4 possible values: abcdef, abcxdef, abcydef and abczdef.

And then of course there's '[whatever]*?'...

Winston
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!