I'm using a regular expression to get variable's names out of an Arduino code (C/C++).
The idea is that when it matches a data-type word like 'int' or 'long' or 'String' ecc... I'm able to get the next word which must be the variable name (otherwise you get a compile error).
I'm using this regular expression:
/(\bint\b|\blong\b|\bString\b)\s*(?<varName>\w+)/g
https://regex101.com/r/cO8lqs/1923
The problem is that node.js throws this error:
SyntaxError: Invalid regular expression: /(\bint\b|\blong\b|\bString\b)\s*(?<varName>\w+)/: Invalid group
and I'm not sure why. I noticed that on regex101.com using pcre(PHP) it highlights the group, but it is not in javascript.
Anyway I tried to compile that regexp on jsfiddle and it works fine.
I'm using this simple code to check it: (click on jsfiddle link and open console. This code looks awful formatted here but I apparently must paste the code here as well)
https://jsfiddle.net/f9wsu6Lh/7/
<!DOCTYPE html>
<html>
<body>
<p>Click the button to replace variable's names with "[Michael and " + variable's name + "]" in the paragraph below:</p>
<p id="demo">int value1 = 0;
int value2=0;
long longvalue =0;
long verylongvalue=0;</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var var_type = ["long", "String"];
var var_type2 = "int";
var str = document.getElementById("demo").innerHTML;
var regexpString="(\\bint\\b";
var_type.map(function(type){
console.log(type);
regexpString += "\|\\b"+type+"\\b";
});
regexpString += ")\\s\*(\?\<varName\>\\w\+)";
//var original_regexp= "\\b"+var_type2+"\\b\\s\*(\?\<varName\>\\S\+)";
var regexp = new RegExp(regexpString, 'g');
var match = regexp.exec(str);
console.log(match);
if(match==null){
console.log('no match found');
}else{
var regexp2 = new RegExp("\\b"+match[2]+"\\b", 'g');
var res2 = str.replace(regexp2, "[Michael and $&]");
while(match !== null) {
console.log(match[2]);
match = regexp.exec(str);
if(match != null){
regexp2 = new RegExp("\\b"+match[2]+"\\b", 'g');
res2 = res2.replace(regexp2, "[Michael and $&]");
}
}
document.getElementById("demo").innerHTML = res2;
}
}
</script>
</body>
</html>
I'm stuck. I don't understand where the problem is.
Any help is really appreciated.