Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

match optional special characters

Tags:

c#

regex

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?

like image 934
Masoumeh Karvar Avatar asked Dec 09 '25 09:12

Masoumeh Karvar


2 Answers

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

like image 75
Taky Avatar answered Dec 11 '25 22:12

Taky


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.

like image 23
w.b Avatar answered Dec 11 '25 23:12

w.b



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!