Skip to content
Advertisement

what I cant splir the char of ‘(‘ using this regexp in javascipt

the var codigo have the value *int a,h;float b,c;a=b*(c+h);

my regex is:

codigo = codigo.split(/(b;|b,|b[=]|b[+]|b[-]|b[*]|b[/]|b[(]|b[)]|bint|bfloat|bchar)/)

and as a output im getting this:

["int", "a", ",", "h", ";", "float", "b", ",", "c", ";", "a", "=", "b", "*", "(c", "+", "h", ")", ";", "$"]

var codigo = 'int a,h;float b,c;a=b*(c+h);'
codigo = codigo.replace(/s/g, '')
codigo = codigo.split(/(b;|b,|b[=]|b[+]|b[-]|b[*]|b[/]|b[(]|b[)]|bint|bfloat|bchar)/).filter(car => car != "")
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:

codigo = codigo.split(/(int|float|char|.)/);

and then remove the empty string elements, using .filter(Boolean).

Working Example:

var codigo = 'int a,h;float b,c;a=b*(c+h);'
codigo = codigo.replace(/s/g, '');
codigo = codigo.split(/(int|float|char|.)/);
codigo = codigo.filter(Boolean);
console.log(codigo);
Advertisement