2010-11-05 138 views
0

我想寫一個正則表達式來測試字符串。該字符串必須以字母數字字符開頭或結尾。正則表達式或運算符

例如。

test - OK 
test$ - OK 
$test - OK 
$ - not OK 
$test$ - not OK 

我可以測試^\w.*$開始與^\w.*$結束。

但我似乎無法將它們合併成類似^.*\w$ | ^\w.*$的東西。

有沒有人有任何想法,甚至更好的正則表達式爲此目的?

+3

您正在使用哪種正則表達式引擎? – JaredPar 2010-11-05 17:34:04

+0

我使用的是C#.NET,但我們使用的是xVal擴展,它將使用javascript函數來測試客戶端的字符串。 – 2010-11-05 17:37:52

回答

0

這應該工作:

^\w.*|.*\w$ 
+0

我用這個,因爲它是最短的。儘管如此,感謝所有答案。 – 2010-11-05 17:48:38

+0

'^ \ w | \ w $'就像4個字符一樣短:) – gnarf 2010-11-05 18:25:43

2

下面應該工作:

/^\w|\w$/ 

雖然\w包括_,所以如果你只想要的字母和數字:

/^[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