I have this function in my TS:
export const parseCode = (code: string, name: string = 'master'): { snippet: string; conf: ProfileSettings } => {
console.log(name);
console.log(code);
console.log(String.raw`# ${name}\n([\s\S]+?)\n\n`);
const match = new RegExp(String.raw`# ${name}\n([\s\S]+?)\n\n`, 'g').exec(code);
console.log('match');
console.log(match);
if (!match) {
throw new Error(`parseProfile: profile ${name} not found`);
}
return { match };
};
The console goes:
master
defaults nosave
Then goes the code
string:
# version
# Betaflight / SPEEDYBEEF405V3 (SBF4) 4.3.2 Apr 7 2023 / 03:15:27 (f156481e9) MSP API: 1.44
# start the command batch
batch start
# master
set gyro_lpf1_static_hz = 0
set gyro_lpf2_static_hz = 300
set dyn_notch_q = 500
set dyn_notch_min_hz = 100
set dyn_notch_max_hz = 500
set gyro_lpf1_dyn_min_hz = 0
set gyro_lpf1_dyn_max_hz = 400
set mag_hardware = NONE
set rc_smoothing_auto_factor = 35
# osd
set osd_vbat_pos = 471
set osd_rssi_pos = 449
And then the rest of the console.logs:
# master\n([\s\S]+?)\n\n
match
null
Uncaught Error: parseCode: profile master not found
Testing regexp is successful both in console and on regexp101. However the regexp execution is failing all the time. What am I missing here?
It is best not to use bare \n
or \r
in regex patterns. Instead, use \s*
or \s+
with multi-line flags for better compatibility.
const match = new RegExp(
String.raw`#\s*{$name}\s+([\s\S]+?)\s*#\s+osd`,
"gm"
).exec(code);
For detailed explanation, see here
#\s*master\s+([^#]+)#\s+osd
may be also possible; see here.