pencilCake
pencilCake

Reputation: 53223

How to match parameter names in an expression?

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:

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

Thanks!

Upvotes: 2

Views: 521

Answers (3)

ICR
ICR

Reputation: 14162

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:

\[[^]]*\]

Upvotes: 2

Kobi
Kobi

Reputation: 137997

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].

Upvotes: 3

Thomas
Thomas

Reputation: 181725

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...

Upvotes: 1

Related Questions