[英]match optional special characters
我在此鏈接中有一個問題,但鏈接中沒有正確的答案。 我有一些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
開頭的字符串,然后匹配:
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);
見演示
這個對我有用:
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
你可以使用lookarounds:
(?<=create function )(\s*\S+\..*?)(?=\s)
它捕獲create function
literal后跟一個或多個空格和另一個空格之間的所有內容,假設匹配的字符串包含至少一個點char。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.