I want to match the following strings:
[anything can be here]
[{anything can be here}]
Can I achieve this using only one regular expression?
I am currently using this one '^\[({)?.+(})?]$', but it will match also:
[anything can be here}]
[{anything can be here]
I need to to match } only if { is used.
Please, note I can use only regular expression match function as I have implemented it as SQL CLR function in order to use it in T-SQL statements.
Basically you can write (verbatim strings):
^\[(?:{.+}|[^]{}]+)]$
You can use something more complicated with a conditional statement (?(condition)then|else):
^\[({)?[^]{}]+(?(1)}|)]$
(if capture group 1 exists, then } else nothing)
But this way is probably less efficient.
I got this working: \[[^{].*[^}]\]|\[\{.*\}\]
EDIT as pointed out by OP something needs to be between parentheses so a 'one or more' match is more suited:
\[[^{].+[^}]\]|\[\{.+\}\] 
see RegEx example here
Your regex ^\[({)?.+(})?]$ will match only an individual string like [{...}] or [{...] because 1) you have anchors (^$), and both curly braces are present in the same pattern.
I suggest using negative look-behinds to avoid matching strings that have just 1 curly brace inside the []-ed string like this:
var rgx = new Regex(@"((?!\[\{[^}]+\]|\[[^{]+\})\[\{?.+?\}?\])");
var tst = "[anything can be here] [{anything can be here}] [anything can be here}] [{anything can be here]";
var mtch = rgx.Matches(tst).Cast<Match>().ToList();
This will make sure you match the []-ed strings even in larger context.
Result:

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