问题
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 aStack
untilCount == 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