Aarif
Aarif

Reputation: 1675

Regex: How to get all matches of a group in a string

I have the following regex

.*context\.Database\.SqlQuery<[A-Za-z]+>\("(?<sqlStatement>.*?[^\\])"\)

and I have the following string

context.Database.SqlQuery<string>("select [Name] from [DomainModel] where UniqueId = 'someGuid'").Single();context.Database.SqlQuery<string>("select [Description] from [DomainModel] where UniqueId = 'someGuid'").Single();

I need to match all occurrences of context.Database.SqlQuery<string>("") and extract the string in between these paranthesis. When I'm testing it with splitting the string like this:

context.Database.SqlQuery<string>("select [Name] from [DomainModel] where UniqueId = 'someGuid'").Single();
context.Database.SqlQuery<string>("select [Description] from [DomainModel] where UniqueId = 'someGuid'").Single();

It works fine. I need to get it working on the previous scenario and output of matches should be like this

the first match

select [Name] from [DomainModel] where UniqueId = 'someGuid'

second match

select [Description] from [DomainModel] where UniqueId = 'someGuid'

here is the regexr for this.

Upvotes: 3

Views: 685

Answers (2)

Talha Junaid
Talha Junaid

Reputation: 2405

Issue is with .* Since . matches with any character except new line. and * quntifies regex to matchs between zero and many times.

You just need to remove .* from the start of given regex. Here is working example of given problem

Upvotes: 1

samanime
samanime

Reputation: 26537

Your problem is the .* at the very beginning. Since that can match everything, that ends up picking up all of the matches except the last one.

If you just drop that, your pattern can pick up each one.

context\.Database\.SqlQuery<[A-Za-z]+>\("(?<sqlStatement>.*?[^\\])"\)

Upvotes: 2

Related Questions