嵌套正则表达式替换C# [英] Nested Regex Replace in C#
问题描述
我真的不认为与正则表达式不错,但我了解的基础知识。我试图找出如何做一个有条件的替代基于在比赛中一定的价值。例如:
I'm not really that good with regex, but I understand the basics. I'm trying to figure out how to do a conditional replace based upon a certain value in the match. For example:
假设我有看起来像这样的一些嵌套的字符串结构:
Suppose I have some nested string structure that look like this:
"[id value]"//id and value are space delimited. id will never have spaces
ID
一些字符串ID名称的 []
项和值
是另外一个嵌套的 [值id]
项。为值
是空的,但我并不担心现在的可能。
id
is some string id that names the []
item and value
is another nested [id value]
item. Its possible for value
to be empty, but I'm not worried about that for now.
如果我有是这样的:
A) "[vehicle [toyota camry]]"
or
B) "[animal [dog rufus]]"
我希望能够调用某个函数根据 ID
作为regex.Replace从内最 [] $ C $执行,获取输出(toString()方法为例) 。C>结构
I'd like to be able to call a certain function (ToString() for example) based upon id
that gets output as the regex.Replace is executed from the inner most []
structure.
从例子去伪代码:
string Return = "{0}";
var 1stValueComboID = GetInteriorValue/IDFrom("[vehicle [toyota camry]]");
//1stValueComboID.ToString() = "Company: Toyota, Make: Camry"
Return = Format.String(Return,1stValueIDCombo.ToString());
var 2stValueComboID = GetSecondValue/IDFrom("[vehicle [toyota camry]]");
//2stValueComboID.ToString() = "Type: Vehicle, {0}"
Return = Format.String(Return,2ndValueIDCombo.ToString());
这显然样本无关与正则表达式,但它希望说明什么样的我正在努力做的。
This sample obviously has nothing to do with regex, but it hopefully illustrates kind of what I'm trying to do.
推荐答案
JoshD正确地指出,你所提出的(有配对括号)这个语法不能使用解析正则表达式。您需要构建具有递归下降的行为自定义分析器。
JoshD correctly points out that this grammar you've proposed (having matching pairs of brackets) cannot be parsed using a regular expression. You need to construct a custom parser with recursive descent behavior.
这篇关于嵌套正则表达式替换C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!