Expresión regular u operador
Pregunta
Estoy intentando escribir una expresión regular a prueba como cadena. La cadena debe comenzar o terminar con un carácter alfanumérico.
por ejemplo.
test - OK
test$ - OK
$test - OK
$ - not OK
$test$ - not OK
Me puede poner a prueba el principio con ^\w.*$
y al final con ^\w.*$
.
Pero me parece que no puede combinarlos en algo así como ^.*\w$ | ^\w.*$
.
¿Alguien tiene alguna idea o incluso una mejor expresión regular para este propósito?
Solución
Esto debería funcionar:
^\w.*|.*\w$
Otros consejos
El siguiente debería funcionar:
/^\w|\w$/
A pesar de \w
incluye _
así que si solo deseas letras y números:
/^[0-9a-zA-Z]|[0-9a-zA-Z]$/
var tests=['test', 'test$', '$test', '$', '$test$'];
var re = /^\w|\w$/;
for(var i in tests) {
console.log(tests[i]+' - '+(tests[i].match(re)?'OK': 'not OK'));
}
// Results:
test - OK
test$ - OK
$test - OK
$ - not OK
$test$ - not OK
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow