Reputation: 9394
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
Reputation: 27609
Figured I might as well provide an answer... To reiterate my points (with modifications):
*
matches 0 or more occurences. You want + probably. [
and ]
from your "any character" matchingPut 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
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
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