Matching and replacing function expressions

时光怂恿深爱的人放手 提交于 2019-12-11 01:39:41

问题


I need to do some very light parsing of C# (actually transpiled Razor code) to replace a list of function calls with textual replacements.

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.

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:

  • find expression start (e.g. Foo.myFunc)
  • Push()/Pop() parentheses on a Stack until Count == 0.
  • Mark this as expression stop
  • replace everything from expression start until expression stop

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?

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 (?).


回答1:


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)(?!))

Replace <func> with your function name.

Useless to say that trollMe("\"(", "((", @"abc""de((f") works as expected.

DEMO



来源:https://stackoverflow.com/questions/37313769/matching-and-replacing-function-expressions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!