• Post Reply Bookmark Topic Watch Topic
  • New Topic

Regular expression - capture groups  RSS feed

 
Bruce Jin
Ranch Hand
Posts: 672
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have this code:


I expect it to print 2 lines:

start=4, end=8, match string=${abc}
start=15, end=19, match string=${xyz}

But it acctually prints only 1 line:

start=4, end=21, match string=${abc} 456 ${xyz}

Why?
Thanks.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because regular expressions as "greedy" and match as much as possible by default. Your ".*" in the braces matches any character, so the first close brace is matched as part of the contents inside the braces.

There are a number of ways to fix this; one would be to use "[^}]*" instead of ".*".
 
Bruce Jin
Ranch Hand
Posts: 672
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks.
"[^}]*" instead of ".*" fixed it.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!