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?
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
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
You can use lookarounds:
(?<=create function )(\s*\S+\..*?)(?=\s)
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.