tags:

views:

72

answers:

3

Hi,

I have a set of expressions representing some formula with some parameters inside. Like:

[parameter1] * [parameter2] * [multiplier]

And many others like this.

I want to use a regular expression so that I can get a list of strings (List<string>) which will have the following inside:

  • [paramter1]
  • [paramter2]
  • [multiplier]

I am not using regular expressions so often; if you have already used something like this I would appreciate if you can share.

Thanks!

+3  A: 

This should do it:

\[\w+\]

Using .net:

string s = "[parameter1] * [parameter2] * [multiplier]";
MatchCollection matches = Regex.Matches(s, @"\[\w+\]");

You may want to use a capturing group here: \[(\w+)\], so you have the parameter's name on Groups[1].

Kobi
Thanks Kobi! I appreciate all the answers, they were quite useful. But I needed exactly what you have described and for .Net. Thanks.
burak ozdogan
+1  A: 

The regex

\[[^]]*\]

will match anything in square brackets:

\[   the opening bracket;
[^]] anything but a closing bracket,
*        repeated zero or more times;
\]   the closing bracket

I'm not sure if that's what you asked for, though...

Thomas
I suspect the brackets were emphasis and not part of the real string.
kenny
+2  A: 

It depends on what the parameters look like.

The general form for the regular expression will be:

\[{something which matches parameter names}\]

If the parameter names can only contain letters, digits and underscores, then you will want something like:

\[\w+\]

This will match parameter names which contain at least one letter, digit or underscore. For example:

[parameter]
[parameter1]
[1st_parameter]
[10]
[a]
[_]

A more usual limitation is to accept parameter names which contain at least one letter, digit or underscore, but must start with a letter:

\[[a-zA-Z]\w*\]

Examples include:

[parameter]
[parameter1]
[first_parameter]
[a]

but it will not match:

[1st_parameter]
[10]
[_]

However, you might decide that it should match anything between square brackets, and that anything can be a parameter name (maybe you want to validate parameter names at a later stage)

\[[^]]+\]

will match anything between square brackets so long as it contains at least 1 character.

If you also want to allow empty square brackets (i.e. match []) then you will want:

\[[^]]*\]
ICR