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)