Exitos
Exitos

Reputation: 29720

Why doesnt this regex match up to the first character specified?

I have...

"Data Source=MYSERVER.dghdev.ds;Initial Catalog=CarPath;Persist Security Info=True;User ID=sa;Password=Password1"

And I wrote the regular expression...

(?=Data Source).*;

But it matches everything up to 'sa'. Which is really annoying I just dont understand why this happens. The .* says any amount of characters and then the ';' should stop at the first one. It doesnt it stops at the fourth one. Why is this? And how do I fix it?

Upvotes: 0

Views: 56

Answers (1)

nhahtdh
nhahtdh

Reputation: 56809

* quantifier is greedy, and it will match as many characters as possible until it cannot match the next token and has to backtrack. In this case, .* will match everything up to the last ; in the string.

If you want to stop at the first ;, you need the lazy version of the quantifier: *?. In other words, your regex should be (?=Data Source).*?;. The lazy quantifier will try to match as few character as possible, as long as the next token can be matched.

Depending on the support of the language, the behavior of quantifiers such as *, +, {n,m} generally can be made lazy by adding ? right after *?, +?, {n,m}?.

Upvotes: 3

Related Questions