2015-09-07 94 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文字后面是一个或多个空格和另一个空间假设匹配的字符串至少包含一个点字符。