简体   繁体   中英

How to ignore all but matches?

I have some source code files where I would like to extract all the comments (C-style) and search them for a specific construct that I can then use in my source generator to make some additional code...

Example:

...
var v = something();//comment I just want to skip
//record Car (
//string CarId This is the CarId
//)
var whatever = ()=>{...};
/*record AnotherCar(
  string CarId This is the CarId
)*/
...

I have 2 problems. First, I cannot figure out how to skip all of the things but the comments, and Second how do I make it only return the records encoded therein? Alternatively, just search for the keywords and attempt to parse from there, but cannot figure that out either.

Old question, but the answer may help someone.

First, I cannot figure out how to skip all of the things but the comments, and Second how do I make it only return the records encoded therein?

You can use Linq query to parse the sequence and select only what you need as given below:

//Extract comments from CSharp code
    public static  IEnumerable<string> GetComments(string text)
        {
            CommentParser comment = new CommentParser();
            var separators = Parse.String("//").Or(Parse.String("/*"));
            Parser<string> comments =
                from _ in Parse.AnyChar.Except(separators).Many().Text()   //ignore
                from c in comment.AnyComment     // select
                select c;
            var result = comments.Many().Parse(text);            
            return result;
        }

Output result

comment I just want to skip
record Car (
string CarId This is the CarId
)
record AnotherCar(
  string CarId This is the CarId
)

Try it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM