在下面的代码中,我想返回此字符串suing regex:'DataSource=xxxtransxxx;Initial Catalog=Sales
'
Sales
可能有也可能没有prefix
,并且上面字符串中的项目之间可能存在或不存在空格。我在下面的代码中尝试了正则表达式,但它不起作用。任何建议表示赞赏,谢谢!
var thestring = @"'SELECT CONVERT(VARCHAR(MAX), [Measures].[EmployeeID ParameterCaption]) AS [EmployeeID]
,CONVERT(VARCHAR(50), [Measures].[Sales Rep Name ParameterCaption]) AS [EmployeeName]
,CONVERT(VARCHAR(50), [Measures].[Manager EmployeeID ParameterCaption]) AS [ManagerEmployeeID]
,CONVERT(MONEY, [MEASURES].[PrevFYYTD])AS PrevFYYTD
,CONVERT(MONEY, [MEASURES].[CurrentFYYTD] ) AS CurrentFYYTD
,CONVERT(VARCHAR(50),[MEASURES].[PCTGrowth] )+''%'' AS [PCTGrowth]
,CONVERT(VARCHAR, [MEASURES].[DollarGrowth] ) AS DollarGrowth
,CONVERT(VARCHAR, [MEASURES].[HasParent] ) AS HasParent
,CONVERT(VARCHAR, [MEASURES].[HasChild] ) AS HasChild
FROM OPENROWSET(''MSOLAP'',''DataSource=xxxtransxxx;Initial Catalog=Sales'' , SET @MDX = ''' WITH;";
Regex rgx = new Regex(@"'\s*DataSource\s*=\s.*trans*(.*Sales) *'", RegexOptions.IgnoreCase);
string result = rgx.Match(thestring).Groups[0].Value;
答案 0 :(得分:1)
您可以使用
\s*DataSource\s*=[^';]+?;\s*Initial *Catalog\s*=[^;']+$
<强>码强>
string resultString = null;
try {
resultString = Regex.Match(subjectString, @"\bDataSource\s*=[^';]+?;\s*Initial *Catalog\s*=[^;']+", RegexOptions.IgnoreCase | RegexOptions.Multiline).Value;
} catch (ArgumentException ex) {
// Syntax error in the regular expression
}
<强>解释强>
@"
(?i) # Match the remainder of the regex with the options: case insensitive (i)
\b # Assert position at a word boundary
DataSource # Match the characters “DataSource” literally
\s # Match a single character that is a “whitespace character” (spaces, tabs, and line breaks)
* # Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
= # Match the character “=” literally
[^';] # Match a single character NOT present in the list “';”
+? # Between one and unlimited times, as few times as possible, expanding as needed (lazy)
; # Match the character “;” literally
\s # Match a single character that is a “whitespace character” (spaces, tabs, and line breaks)
* # Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
Initial # Match the characters “Initial” literally
\ # Match the character “ ” literally
* # Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
Catalog # Match the characters “Catalog” literally
\s # Match a single character that is a “whitespace character” (spaces, tabs, and line breaks)
* # Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
= # Match the character “=” literally
[^;'] # Match a single character NOT present in the list “;'”
+ # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
"