3

I have a question that has asked before in this link, but there is no right answer in the link. I have some sql query text and I want to get all function's names (the whole name, contain schema) that has created in these. my string may be like this:

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

and I want to get both [SN].[FunctionName] and SN.FunctionName, I tried this regex :

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

but this returns only the first statement, how can I make those brackets optional in the regex expression?

Community
  • 1
  • 1
Masoumeh Karvar
  • 791
  • 1
  • 14
  • 32

3 Answers3

1

To make some subpattern optional, you need to use the ? quantifier that matches 1 or 0 occurrences of the preceding subpattern.

In your case, you can use

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

The regex matches a string starting with create function and then matching:

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

See demo

enter image description here

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
1

This one works for me:

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

See test example: http://regexr.com/3bo0e

Taky
  • 5,284
  • 1
  • 20
  • 29
1

You can use lookarounds:

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

Demo on regex101.com

It captures everything between create function literal followed by one or more spaces and another space assuming the matched string contains at least one dot char.

w.b
  • 11,026
  • 5
  • 30
  • 49