Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
287 views
in Technique[技术] by (71.8m points)

javascript - How to extract body of this callback-ish style function using regex?

I'm trying to extract body of this function using JavaScript

J_Script(void, someName, (const char *str), {
   function howdy() {
      console.log("What's up");
   }

   howdy();
});

I have attempted the following regex,

(J_Scripts?)([^.])([w|,|s|-|_|$]*)(.+?{)([^.][s|S]*(?=}))

It capture most of it but fails to detect end of the function thus corrputing the end result.

The end result need to looks like this,

   function howdy() {
      console.log("What's up");
   }

   howdy();

Yes, I know Regex maybe be not perfect for this but I don't have time to create an AST and I'm looking to do some pre-processing using Javascript.

Worth noting that the function will always ends with }); not })

question from:https://stackoverflow.com/questions/65940664/how-to-extract-body-of-this-callback-ish-style-function-using-regex

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Assuming your function has the substring }); starting at character 0 at the start of the function closing line (i.e. is flush to the left), you can use

(J_Scripts?)([^.])([w|,|s|-|_|$]*)(.+?{)([^.][s|S]*?(?=(^});)))

With the multiline flag

The only modifications from your original are:

(J_Scripts?)([^.])([w|,|s|-|_|$]*)(.+?{)([^.][s|S]*?(?=^});))
//                                                          ^   ^
//                                                          |   |
//                                                 non-greedy   beginning of line

If your functions have a fixed offset indentation, you can exploit that just the same, using /^ {x}/ where x is a digit representing whatever indentation count you have.

This also handles nested }); or whatever else might be in the function, so long as it's indented correctly.

If you want to capture the closing });, add a capture group to the above pattern:

(J_Scripts?)([^.])([w|,|s|-|_|$]*)(.+?{)([^.][s|S]*?(?=(^});)))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...