匹配可选特殊字符

3

我有一个问题,在这个链接上问过了,但是链接里没有正确的答案。我有一些 SQL 查询文本,我想得到其中创建的所有函数名(完整名称,包括模式)。

我的字符串可能是这样的:

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

我希望能够同时获取 [SN].[FunctionName] 和 SN.FunctionName, 我尝试了这个正则表达式:

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

但是这只返回第一个语句,如何使正则表达式中的括号可选?

你不想也获取 functionName 吗? - Wiktor Stribiżew
是的,我想要并且我将使用'()'来捕获它 - Masoumeh Karvar
那么,请检查我的答案。你接受的答案在示例代码中至少有一个严重问题,并且不允许没有点和方括号的名称。 - Wiktor Stribiżew
你是对的。但是你的答案也返回了无模式函数,而我不需要那个(我已经提到了我需要的答案)。此外,Taky的答案有一些有用的描述(尽管你也添加了描述,但是在我检查之后)。但是你帮助了我,我很感激。 - Masoumeh Karvar
所以,您只想要那些函数名称中带有句点的吗?好的,我明白了。 - Wiktor Stribiżew
3个回答

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);

看看 演示

enter image description here


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


1
您可以使用“lookarounds”:
(?<=create function )(\s*\S+\..*?)(?=\s)

在regex101.com上的演示

它捕获以create function文字字面量开头,后跟一个或多个空格和另一个空格之间的所有内容,假设匹配的字符串至少包含一个点字符。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接