Tomtom
Tomtom

Reputation: 9394

c# Regular expression for words in brackets with separator

I need to parse a text and check if between all squared brackets is a - and before and after the - must be at least one character. I tried the following code, but it doesn't work. The matchcount is to large.

Regex regex = new Regex(@"[\.*-.*]");
MatchCollection matches = regex.Matches(textBox.Text);

SampleText:

Node
  (Entity [1-5])

Upvotes: 0

Views: 730

Answers (3)

Chris
Chris

Reputation: 27609

Figured I might as well provide an answer... To reiterate my points (with modifications):

  1. * matches 0 or more occurences. You want + probably.
  2. square brackets are special characters and will need to be escaped. They are used to define sets of characters.
  3. You will probably want to exclude [ and ] from your "any character" matching

Put this all together and the following should do you better:

Regex regex = new Regex(@"\[[^-[\]]+-[^[\]]+\]");

Although its a little messy the key thing is that [^[\]] means any character except a square bracket. [^-[\]] means that but also disallows -. This is an optimisation and not required but it just reduces the work the regular expression engine has to do when working out the match. Thanks to ridgerunner for pointing out this optimisation.

Upvotes: 3

urlreader
urlreader

Reputation: 6605

 string txt = "(Entity [1-5])";
 Regex reg = new Regex(@"\[.+\-.+\]");

if it is for #:

 string txt = "(Entity [1-5])";
 Regex reg = new Regex(@"\[\d+\-\d+\]");

Upvotes: 0

ean5533
ean5533

Reputation: 8994

Square brackets mean something special in Regexes, you'll need to escape them. Additionally, if you want at least one character then you need to use + rather than *.

Regex regex = new Regex(@"\[.+-.+\]");
MatchCollection matches = regex.Matches(textBox.Text);

Upvotes: 1

Related Questions