Accept only all regular subexpressions

3

I have a word, for example, hola , and I want to make a regular expression that accepts all subexpressions. That is, you have to accept h , ho , hol and hola .

For this I do ^(hola)|(hol)|(ho)|(h)$ Is there a way without repeating the letters? What would it be?

If I do ^h?o?l?a?$ accept all subexpressions, but have the problem that it also accepts ha , which is not a subexpression.

Code that generates the general regular expression:

function generar_subexpresión(expresión)
{
  var salida = ""
  var subexpresión = expresión
  for(var i=0;i<expresión.length;i++)
  {
    if(i>0){salida+="|"}
    salida += "(" + subexpresión.join("") + ")"
    subexpresión = subexpresión.slice(0,-1)
  }
  return "^" + salida + "$"
}
var palabra = "hola".split("")
var resultado = generar_subexpresión(palabra)
console.log(resultado)

palabra = ["\d","[a-z]","3"]
resultado = generar_subexpresión(palabra)
console.log(resultado)
    
asked by ArtEze 28.11.2018 в 21:11
source

1 answer

3

Generates the groups in this way (?:x|$) , means that it finds this exact letter or is the end of the expression, if it respects the order of the letters.

function generar_subexpresion(expresion) {
  return '^' + expresion
                .split('')
                .map(x => '(?:${x}|\$)')
                .join('');
}

var texto = generar_subexpresion('hola');
console.log(texto);

var regex = new RegExp(texto);

var pruebas = ['hola', 'hol', 'ho', 'h', 'hoa', 'hla', 'ha'];

for (var i = 0; i < pruebas.length; i++) {
  console.log(pruebas[i], ':', regex.test(pruebas[i]));
}
    
answered by 28.11.2018 / 21:35
source