3

我有一个字符串,它的值如下

{ctrl1} + {ctrl2}
({ctrl1} / {ctrl2}) * {ctrl3}
if ({ctrl1} > {ctrl2}) then {ctrl1} * 10 else {ctrl} + {ctrl2} endif

可能有几个这样的公式。这将在字符串变量中可用。我需要提取所有{..}值。

因此,在示例 1 中,我应该提取{ctrl1}, {ctrl2}。在 Example2 中,我应该提取{ctrl1}, {ctrl2}, {ctrl3}. 在示例 3 中,我应该提取{ctrl1}, {ctrl2}

有人可以帮我用正则表达式吗?

4

4 回答 4

2

您可能想要类似{[^}]+}.

但是请注意,这不会处理像{hello{2}}. 你可能需要一个真正的解析器来处理这样的事情。

于 2012-07-07T13:36:39.103 回答
1

类似的东西{\S+?}应该可以解决问题。

于 2012-07-07T13:31:29.023 回答
0

您可以结合正则表达式和 LINQ 并执行以下操作:

Regex.Matches(input, "{.*?}").Cast<Match>().Select(m => m.Value).Distinct();

假设{ctrl}是上一个示例中的错字。

于 2012-07-07T13:55:53.490 回答
-2
private void TrimControlNames()
    {
        if (txtFormula.Text.Trim().Length > 0)
        {
            string formula = txtFormula.Text.Trim();

            string pattern1 = "{[a-zA-Z0-9$_ ]+}"; //to identify control placeholders
            StringBuilder names = new StringBuilder();
            foreach (Match m in Regex.Matches(formula, pattern1))
            {
                if (m.Value.Contains(" "))
                {
                    string str = m.Value.Replace(" ", string.Empty); //It is ok to remove like this since control names are not allowed to have spaces.
                    formula = formula.Replace(m.Value, str);
                }

            }

            txtFormula.Text = formula;
        }

    }

此方法执行我的预期。

于 2012-07-07T13:51:39.340 回答