Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression - Match End if Start is Match

Tags:

c#

.net

regex

sql

tsql

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.

like image 264
gotqn Avatar asked Apr 28 '15 08:04

gotqn


3 Answers

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.

like image 155
Casimir et Hippolyte Avatar answered Oct 19 '22 00:10

Casimir et Hippolyte


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

like image 42
SierraOscar Avatar answered Oct 19 '22 01:10

SierraOscar


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:

enter image description here

like image 2
Wiktor Stribiżew Avatar answered Oct 19 '22 01:10

Wiktor Stribiżew