gpt4 book ai didi

c# - 多个级别的特殊字符串模式的正则表达式

转载 作者:行者123 更新时间:2023-11-30 16:12:44 26 4
gpt4 key购买 nike

我需要评估一个类似于下面给出的字符串模式,我对编写这种复杂的表达式很陌生

<%(ddlValue){DropDownList}[SelectedValue]%>
// this has three part (Control Name) {Control Type} [Control Property]

我尝试了很多正则表达式和其他工具,例如 RegExr,但都没有用。我必须在四个级别上执行此操作,如下面的代码所示。所以这就是我所做的:

string regex = "/[<%](.*?)[%>]/g"; // Regex to match "<% %>" pattern
Match mtch = Regex.Match(strQuery, regex, RegexOptions.Singleline);
string strControlName = "";
string strControlType = "";
string strControlProp = "";
if (mtch.Success)
{
string strVal = mtch.Value;
Match mtchControlName = Regex.Match(strVal, "/[(]\S)/");
// Regex to match "()" i.e. control name ("ddlValue" in above example)
if (mtchControlName.Success)//Match control Name
{
strControlName = mtchControlName.Value;
Match mtchControlType = Regex.Match(strVal, "/[{]\s[}]/");
// Regex to match "[]" i.e. control type
if (mtchControlType.Success) // Match Control Type
{
strControlType = mtchControlType.Value;
Match mtchControlProp = Regex.Match(strVal, "/[(]\S[)]/");
// Regex to match "[]" i.e. control property
if (mtchControlProp.Success) // Match Control Prop
{
strControlProp = mtchControlProp.Value;
}
}
}
}

最佳答案

您可以在单个正则表达式中执行此操作。尽可能具体,你可以这样做:

Regex regexObj = new Regex(
@"\( # Match (
( # Capture in group 1:
[^()]* # Any number of characters except ()s
) # End of group 1
\) # Match )
\{([^{}]*)\} # The same for {...} into group 2
\[([^\[\]]*)\] # The same for [...] into group 3",
RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);

然后你用例

Match matchResults = regexObj.Match(subjectString);

获取 Match 对象。通过

访问子匹配
matchResults.Groups(n).Value   // insert 1, 2 or 3 for n

查看live on regex101.com .

关于c# - 多个级别的特殊字符串模式的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22551252/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com