2015-09-07 150 views
3

我有一個問題在this link之前詢問過,但鏈接中沒有正確的答案。我有一些SQL查詢文本,我想獲得所有在這些中創建的函數的名稱(全名,包含模式)。 我的字符串可能是這樣的:匹配可選的特殊字符

create function [SN].[FunctionName] test1 test1 ... 
create function SN.FunctionName test2 test2 ... 
create function functionName test3 test3 ... 

,我想同時獲得[SN] [FunctionName]和SN.FunctionName, 我想這個表達式:

create function (.*?\]\.\[.*?\]) 

但這隻能返回第一條語句,我怎樣才能使正則表達式中的那些括號可選?

+0

難道你不想獲得'functionName'嗎? –

+0

是的,我想要我用'()'來捕獲它 –

+0

然後,請檢查我的答案。您接受的那個在示例代碼中至少有1個嚴重問題,並且不允許沒有句號和方括號的名稱。 –

回答

1

這一個適合我:

create function\s+\[?\w+\]?\.\[?\w+\]? 

val regExp = "create function" + //required string literal 
    "\s+" + //allow to have several spaces before the function name 
    "\[?" + // '[' is special character, so we quote it and make it optional using - '?' 
    "\w+" + // only letters or digits for the function name 
    "\]?" + // optional close bracket 
    "\." + // require to have point, quote it with '\' because it is a special character 
    "\[?" + //the same as before for the second function name 
    "\w+" + 
    "\]?" 

見測試例:http://regexr.com/3bo0e

+0

此代碼在C#中無法正常工作。 –

1

要使某些子模式可選,您需要使用與匹配的?量詞符,該匹配項的前一個子模式爲的出現次數爲1或0次。

在你的情況,你可以使用

create[ ]function[ ](?<name>\[?[^\]\s.]*\]?\.\[?[^\]\s.]*\]?) 
          ^  ^^  ^

正則表達式開始create function,然後匹配字符串匹配:

var rx = new Regex(@"create[ ]function[ ] 
      (?<name>\[?  # optional opening square bracket 
       [^\]\s.]*  # 0 or more characters other than `.`, whitespace, or `]` 
       \]?    # optional closing square bracket 
       \.    # a literal `.` 
       \[?    # optional opening square bracket 
       [^\]\s.]*  # 0 or more characters other than `.`, whitespace, or `]` 
       \]?   # optional closing square bracket 
      )", RegexOptions.IgnorePatternWhitespace); 

demo

enter image description here

1

您可以使用lookarounds:

(?<=create function)(\s*\S+\..*?)(?=\s) 

Demo on regex101.com

它捕獲之間的一切create function文字後面是一個或多個空格和另一個空間假設匹配的字符串至少包含一個點字符。