开发者

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<str开发者_Python百科ing>) 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!


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


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:

\[[^]]*\]


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜