0

I'd like to capture the value of the Initial Catalog in this string:

"blah blah Initial Catalog = MyCat'"

I'd like the result to be: MyCat

There could or could not be spaces before and after the equal sign and there could or could not be spaces before the single quote.

Tried this and various others but no go:

/Initial Catalog\s?=\s?.*\s?\'/

Using .Net.

1
  • What results are you getting? Commented Jun 5, 2012 at 21:20

3 Answers 3

2

You need to put parentheses around the part of the string that you would like to match:

/Initial Catalog\s*=\s*(.*?)\s*'/

Also you would like to exclude as many spaces as possible before the ', so you need \s* rather than \s?. The .*? means that the extracted part of the string doesn't take those spaces, since it is now lazy.

Sign up to request clarification or add additional context in comments.

6 Comments

This will leave empty space round the desired match. Example Input: "blah blah Initial Catalog = MyCat'" and "blah blah Initial Catalog =MyCat ' "
Are you sure? The update still has spaces in groups 1. Also, why is the ' escaped in the end? I saw the OP do it also but doubt if it is needed
Not quit it seems. The spaces before MyCat in "Initial Catalog = MyCat'" are also matched.
Oh dear yes, should be fixed. Apologies for the many half-complete answers.
Thats fixed now. Sorry to inform you that "blah blah Initial Catalog SOME SPACES HERE THAT SO DOES NOT SHOW IN COMMENTS= MyCat'" will not result in a match. Spaces before the = were possible. Hope you have a regression test suite ;)
|
1

This is a nice regex

= *(.*?) *'

Use the idea and add \s and more literal text as needed.

In C# group 1 will contain the match

string resultString = null;
try {
    Regex regexObj = new Regex("= *(.*?) *'");
    resultString = regexObj.Match(subjectString).Groups[1].Value;
} catch (ArgumentException ex) {
    // Syntax error in the regular expression
}

3 Comments

Why do you have a question mark after the .*? .* will already match an empty string.
@gereeter If you make it greedy (so drop the ?) you will match the spaces after MyCat in "blah blah Initial Catalog =MyCat ' " While only MyCat should be matched
This one seems the cleanest for me. Thanks everyone!!
0
Regex rgx = new Regex(@"=\s*([A-z]+)\s*'");
String result = rgx.Match(text).Groups[1].Value;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.