匹配和替换函数表达式 [英] Matching and replacing function expressions
问题描述
我需要做的C#(实际上的 transpiled剃刀代码)取代的功能列表,调用与文本替换。
I need to do some very light parsing of C# (actually transpiled Razor code) to replace a list of function calls with textual replacements.
如果给包含一组 {Foo.myFunc:\def\}
应该替换这个代码:
If given a set containing {"Foo.myFunc" : "\"def\"" }
it should replace this code:
var res = "abc" + Foo.myFunc(foo, Bar.otherFunc( Baz.funk()));
与此:
with this:
var res = "abc" + "def"
我不在乎如果您对本嵌套表达式
I don't care about the nested expressions.
这似乎相当琐碎,我想我应该能避免使用像这样的映射集的每一个成员建立一个整个C#编译器:
This seems fairly trivial and I think I should be able to avoid building an entire C# parser using something like this for every member of the mapping set:
- 找到表达启动(例如
Foo.myFunc
) -
按()
/POP()
括号在的Stack
直到计数== 0
。 - 标记这是表达停止
- 取代一切从表达式开始到停止的表达
- find expression start (e.g.
Foo.myFunc
) Push()
/Pop()
parentheses on aStack
untilCount == 0
.- Mark this as expression stop
- replace everything from expression start until expression stop
但也许我并不需要...有一个(可能是内置在).NET库,能为我做到这一点?计数不可能在语言的家庭,稀土是,但也许是的扩展的在C#中的正则表达式语法,可以处理这个不知何故使用反向引用?
But maybe I don't need to ... Is there a (possibly built-in) .NET library that can do this for me? Counting is not possible in the family of languages that RE is in, but maybe the extended regex syntax in C# can handle this somehow using back references?
编辑:
至于这个答案的评论演示仅仅统计括号会没有足够的一般,因为像 trollMe(()
将甩开这些算法,只有真正的解析会话足够了,我猜(?)。
edit:
As the comments to this answer demonstrates simply counting brackets will not be sufficient generally, as something like trollMe("(")
will throw off those algorithms. Only true parsing would then suffice, I guess (?).
推荐答案
对于普通的字符串的诀窍是:
The trick for a normal string will be:
(?>"(\\"|[^"])*")
(大于(\\[^])*?)
一个逐字字符串:
A verbatim string:
(?>@"(""|[^"])*")
也许这可以帮助,但我不知道,这将适用于所有情况>
Maybe this can help, but I'm not sure that this will work in all cases:
<func>(?=\()((?>/\*.*?\*/)|(?>@"(""|[^"])*")|(?>"(\\"|[^"])*")|\r?\n|[^()"]|(?<open>\()|(?<-open>\)))+?(?(open)(?!))
替换< FUNC方式>
与您的函数名
没用的,说 trollMe(\(,((@ABC德((F)
作品如预期。
Useless to say that trollMe("\"(", "((", @"abc""de((f")
works as expected.
这篇关于匹配和替换函数表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!