0

Given a dummy function as such:

#include "DigiKeyboard.h"
        
void setup() {
            
#start_shift_3

DigiKeyboard.sendKeyStroke(0);

#end_shift_3

}
        
   void loop() {

  DigiKeyboard.delay(2000);

     }

I tried to get the content of the Setup function between the brackets and I tried

/[setup]+[(][a-zA-Z0-9=',]+[)][{]\n(.+?)\n+\s+[}]/gs

To get the result I want

#start_shift_3

DigiKeyboard.sendKeyStroke(0);

#end_shift_3

The problem is that the code was not written correctly because it works in the Regex site

But it doesn't work with javascript code and I think the reason is

regex single line flag /s

I searched a lot and read on Stackoverflow and the answers are not appropriate for the situation

My Regex

So even though the code works there, it won't work with JavaScript

var string = `


#include "DigiKeyboard.h"

void setup(){

#start_shift_3

DigiKeyboard.sendKeyStroke(0);

#end_shift_3

}

   void loop() {

  DigiKeyboard.delay(2000);

     }
        

`;



const regex = new RegExp("[setup]+[(][)][{]\n(.+?)\n+\s+[}]');

console.log(string.match(regex) == null);

2
  • wouldn't that fail if there is } inside the function? Commented Sep 28, 2022 at 22:15
  • @ITgoldman I don't know, but I think I've read before. This can be overcome by making it \} But in my case } will not be used inside the function Commented Sep 28, 2022 at 22:29

1 Answer 1

1

This regex extracts the content within { ... } of setup:

var string = `

#include "DigiKeyboard.h"

void setup(){

#start_shift_3

DigiKeyboard.sendKeyStroke(0);

#end_shift_3

}

   void loop() {

  DigiKeyboard.delay(2000);

     }
`;

const m = string.match(/\bsetup\s*\(\)\s*\{\s*([^\}]*)/);
console.log(m ? m[1] : '(no match)');

Explanation of regex:

  • \b -- word boundary
  • setup -- expect literal setup string
  • \s*\(\)\s* -- scan over optional whitespace, (), whitespace
  • \{\s* -- scan over opening { and optional whitespace
  • ([^\}]*) -- capture group scanning over everything not a closing }

Note that this will fail if your setup function contains curly braces. In that case you would need a proper language parser, or a multi-step regex that annotates the nesting level of the curly braces, so that you can identify the proper closing brace of the function.

Sign up to request clarification or add additional context in comments.

1 Comment

I won't need to add curly braces inside the function so this is a perfect answer Thank you for the very useful answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.