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
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);
CodePudding user response:
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 boundarysetup
-- expect literalsetup
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.