c# - 匹配可选的特殊字符

标签 c# regex

我之前在 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 (.*?\]\.\[.*?\])

但这只返回第一条语句,我怎样才能在正则表达式中使这些括号可选?

最佳答案

这个对我有用:

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

关于c# - 匹配可选的特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32438258/

相关文章:

c# - LINQ 双向区分多个属性

javascript - 在两个单词之间应用正则表达式

php - 为什么 preg_match 不起作用?

Javascript 正则表达式拆分

c# - 无法获取默认构造函数

c# - 通用类型。没有装箱转换或类型参数转换

c# - 如何尝试/捕获所有异常

c# - 电子邮件 ID 的正则表达式检查失败

java - 正则表达式替换 spring :message tags with th:text equivalent

c# - Asp.net core默认路由