the var codigo have the value *int a,h;float b,c;a=b*(c+h);
my regex is:
JavaScript
x
2
1
codigo = codigo.split(/(b;|b,|b[=]|b[+]|b[-]|b[*]|b[/]|b[(]|b[)]|bint|bfloat|bchar)/)
2
and as a output im getting this:
JavaScript
1
2
1
["int", "a", ",", "h", ";", "float", "b", ",", "c", ";", "a", "=", "b", "*", "(c", "+", "h", ")", ";", "$"]
2
JavaScript
1
4
1
var codigo = 'int a,h;float b,c;a=b*(c+h);'
2
codigo = codigo.replace(/s/g, '')
3
codigo = codigo.split(/(b;|b,|b[=]|b[+]|b[-]|b[*]|b[/]|b[(]|b[)]|bint|bfloat|bchar)/).filter(car => car != "")
4
console.log(codigo)
why after the ‘*’ the ‘(‘ isnt splitting right ? when the ‘)’ its doing correctly?
Advertisement
Answer
In Regular Expressions, since .
represents any character, it should be enough to split by the following regex:
JavaScript
1
2
1
codigo = codigo.split(/(int|float|char|.)/);
2
and then remove the empty string elements, using .filter(Boolean)
.
Working Example:
JavaScript
1
5
1
var codigo = 'int a,h;float b,c;a=b*(c+h);'
2
codigo = codigo.replace(/s/g, '');
3
codigo = codigo.split(/(int|float|char|.)/);
4
codigo = codigo.filter(Boolean);
5
console.log(codigo);