[英]Regular expression to retrieve text from a string
I have a string which will have values like 我有一个字符串,其值将是
{ctrl1} + {ctrl2}
({ctrl1} / {ctrl2}) * {ctrl3}
if ({ctrl1} > {ctrl2}) then {ctrl1} * 10 else {ctrl} + {ctrl2} endif
there could be several formulas like this. 可能有几个像这样的公式。 This will be available in a string variable.
这将在字符串变量中提供。 I need extract all
{..}
values. 我需要提取所有
{..}
值。
So, in example1, I should extract {ctrl1}
, {ctrl2}
. 所以,在example1中,我应该提取
{ctrl1}
, {ctrl2}
。 In Example2, I should extract {ctrl1}
, {ctrl2}
, {ctrl3}
. 在Example2中,我应该提取
{ctrl1}
, {ctrl2}
, {ctrl3}
。 In example3, I should extract {ctrl1}
, {ctrl2}
. 在example3中,我应该提取
{ctrl1}
, {ctrl2}
。
Can someone please help me with a regex for this? 有人可以帮我一个正则表达式吗?
You probably want something like {[^}]+}
. 你可能想要
{[^}]+}
。
Note however that that won't handle recursive stuff like {hello{2}}
. 但请注意,它不会处理像
{hello{2}}
这样的递归内容。 You'll probably need an actual parser for things like that. 你可能需要一个真正的解析器来做这样的事情。
像{\\S+?}
这样的东西应该可以解决问题。
You can combine regex and LINQ and do this: 你可以结合正则表达式和LINQ并执行此操作:
Regex.Matches(input, "{.*?}").Cast<Match>().Select(m => m.Value).Distinct();
Assuming {ctrl}
was a typo in the last example. 假设
{ctrl}
在上一个例子中是一个拼写错误。
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;
}
}
This method performs what I expected. 这种方法执行我的预期。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.