Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 643
Aarif Avatar asked Jan 28 '26 17:01

Aarif


2 Answers

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>.*?[^\\])"\)
like image 191
samanime Avatar answered Jan 31 '26 10:01

samanime


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

like image 26
Talha Junaid Avatar answered Jan 31 '26 09:01

Talha Junaid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!