我可以在格式为 {key-value}Some text{/key}
的文本区域内有 0 个或多个子字符串,
例如这是我的{link-123}测试{/link}文本区域
我想遍历匹配此模式的任何项目,根据键和值执行和操作,然后用新字符串替换此子字符串(由基于键的操作检索的 anchor 链接) .
我如何在 C# 中实现这一点?
最佳答案
如果这些标签没有嵌套,那么你只需要遍历文件一次;如果可以嵌套,则需要对每一层嵌套进行一次迭代。
此答案假定大括号仅作为标记定界符出现(而不是,例如,在注释内部):
result = Regex.Replace(subject,
@"\{ # opening brace
(?<key>\w+) # Match the key (alnum), capture into the group 'key'
- # dash
(?<value>\w+) # Match the value (alnum), capture it as above
\} # closing brace
(?<content> # Match and capture into the group 'content':
(?: # Match...
(?!\{/?\k<key>) # (unless there's an opening or closing tag
. # of the same name right here) any character
)* # any number of times
) # End of capturing group
\{/\k<key>\} # Match the closing tag.",
new MatchEvaluator(ComputeReplacement), RegexOptions.Singleline | RegexOptions.IgnorePatternWhitespace);
public String ComputeReplacement(Match m) {
// You can vary the replacement text for each match on-the-fly
// m.Groups["key"].Value will contain the key
// m.Groups["value"].Value will contain the value of the match
// m.Groups["value"].Value will contain the content between the tags
return ""; // change this to return the string you generated here
}
关于c# - 如何匹配正则表达式模式并从中提取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14736697/