C# 匹配可选的特殊字符

C# 匹配可选的特殊字符,c#,regex,C#,Regex,我有一个问题,以前问过,但在链接中没有正确的答案。我有一些sql查询文本,我想获取在这些文本中创建的所有函数名(全名、包含模式)。 我的字符串可能是这样的: create function [SN].[FunctionName] test1 test1 ... create function SN.FunctionName test2 test2 ... create function functionName test3 test3 ... 我想同时得到[SN].[Func

我有一个问题,以前问过,但在链接中没有正确的答案。我有一些sql查询文本,我想获取在这些文本中创建的所有函数名(全名、包含模式)。 我的字符串可能是这样的:

 create function [SN].[FunctionName]   test1 test1 ...
 create function SN.FunctionName   test2 test2 ...
 create function functionName   test3 test3 ...
我想同时得到[SN].[FunctionName]和SN.FunctionName, 我试过这个正则表达式:

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

但这只返回第一条语句,如何使这些括号在正则表达式中成为可选的?

要使某些子模式成为可选的,您需要使用与前面子模式的1次或0次匹配的
量词

在您的情况下,您可以使用

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

这一款适合我:

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+" + 
  "\]?"

请参阅测试示例:

您可以使用lookarounds:

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

(?您不想同时获取
functionName
?是的,我想要并且我会使用“()“要捕获它,请检查我的答案。您接受的答案在示例代码中至少有一个严重问题,并且不允许名称没有句点和方括号。您是对的。但是您的答案也返回无模式的函数,我不希望这样(我提到了我需要的答案)。此外,Taky的答案有一些有用的描述(虽然你也添加了描述,但是在我检查之后)。但是你帮助了我,我很感谢。所以,你只想要那些有句号的函数名?好的,我明白了。
(?<=create function )(\s*\S+\..*?)(?=\s)