简体   繁体   中英

Regex to find substring between two strings

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.

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.

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
}
Regex rgx = new Regex(@"=\s*([A-z]+)\s*'");
String result = rgx.Match(text).Groups[1].Value;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM