C# Regex to replace entire function's contents -


i'm having bit of trouble getting expression work replace entire contents of function. example

void function1 (void) {      junk here();      other junk here      {          blah blah blah      } } 

i'd replace contents of function predefined value ie

void function1 (void) {      else here } 

this have doesn't seem work. trying capture first part of function , ending curly brace on new line itself. i'm pretty new regular expressions forgive me if makes no sense

text = regex.replace(text, @"(function1)*?(^}$))", replace, regexoptions.multiline); 

any ideas doing wrong or how should go differently?

this seems work:

/function1(?:.|\n)*?^}/m 

see http://regexr.com/3geoq.

i think major issue regular expression (function1)*, matches string "function1" 0 or more times. example matching strings "" , "function1function1function1". meant (function1).*, unless things work differently in .net's regular expression engine, . won't match newlines. used (?:.|\n) instead include newlines. dropped captures, since response question references didn't seem indicate using them.

you had right parenthesis in regular expression have expected cause error.

full working c# code:

using system; using system.text.regularexpressions;  namespace regex {     class program     {         static void main(string[] args)         {             var text = @"something here void anotherfunc(int x) {  }  void function1 (void) {      junk here();      other junk here      {          blah blah blah      } }  int main() { }";              var replacement = @"function1 (void)     else here }";              console.out.writeline(regex.replace(text, @"function1(?:.|\n)*?^}", replacement, regexoptions.multiline));         }     } } 

output:

something here void anotherfunc(int x) {  }  void function1 (void)     else here }  int main() { } 

Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -