espressione regolare o l'operatore
Domanda
Sto cercando di scrivere un'espressione regolare per testare come stringa. La stringa deve iniziare o terminare con un carattere alfanumerico.
ad es.
test - OK
test$ - OK
$test - OK
$ - not OK
$test$ - not OK
I può testare l'inizio con ^\w.*$
e la fine con ^\w.*$
.
Ma io non riesco a combinarli in qualcosa di simile ^.*\w$ | ^\w.*$
.
Qualcuno ha qualche idea o anche un'espressione regolare meglio per questo scopo?
Soluzione
Questo dovrebbe funzionare:
^\w.*|.*\w$
Altri suggerimenti
Il seguente dovrebbe funzionare:
/^\w|\w$/
Anche se \w
comprende _
quindi se desideri solo lettere e numeri:
/^[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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow