0

I have the following regular expression:

Defaults(.*)Class=\"(?<class>.*)\"(.*)StorePath=\"(?<storePath>.*)\"

And the following string:

Defaults Class="Class name here" StorePath="Any store path here" SqlTable="SqlTableName"

I'm trying to achieve the following:

class Class name here
storePath Any store path here

But, what I'm getting as a result is:

class Class name here
storePath Any store path here SqlTable="SqlTableName"

How to stop before the Sqltable text?

The language is C# and the regex engine is the built in for .NET framework.

Thanks a lot!

imnotaduck
  • 177
  • 1
  • 12

3 Answers3

1

The solution proposed by @ahmed-abdelhameed solves the problem, I forgot the non-greedy.

Defaults(.*)Class=\"(?<class>.*)\"(.*)StorePath=\"(?<storePath>.*?)\"

Thanks!

imnotaduck
  • 177
  • 1
  • 12
1

In the storePath group, you're matching zero or more times of any character (greedy match). What greedy match means is that it will return as many characters as possible, so it keeps matching characters until it reaches the last occurrence of ".

What you need to do is to convert your greedy match into a lazy match by replacing .* with .*?. What lazy match means is that it will return as few characters as possible, so in your case, it'll keep matching character until it reaches the first occurrence of ".

Simply replace your regex with:

Defaults(.*)Class=\"(?<class>.*)\"(.*)StorePath=\"(?<storePath>.*?)\"

References:

0

Alittle easier to read:

Class="(.+?)".+?StorePath="(.+?)"

The .+? is saying match un-greedy, basically match as little as possible. That will cause it to capture up to the next "

d g
  • 1,594
  • 13
  • 13