2011-12-15 53 views
0

我現在有一個javascript文件的正則表達式:更改正則表達式只接受指定的字符?

function (value) { 
    regex = new RegExp("[\<|\>|\"|\'|\%|\;|\(|\)|\&|\_|\.]", "i"); 
    return !regex.test(value); 
} 

勝於指定不準什麼角色,我怎麼能說出允許哪些角色?我想要的字符是a-z A-Z 0-9(也是實際的字符「 - 」,但不在開始或結束處,僅在中間)。先謝謝了。

+0

對不起,還應該有最少6個字符輸入請...目前,它混淆哪個答案是正確的,因爲每個答案都有一票! – 2011-12-15 22:28:16

+0

我用最小6字符解決方案更新了我的答案 – stema 2011-12-15 22:34:19

+0

對於長度要求,爲什麼不測試字符串的長度,如果正則表達式匹配?看到我的答案。 – fge 2011-12-15 22:35:17

回答

3

regex = new RegExp("^[a-zA-Z0-9]+(?:-[a-zA-Z0-9]+)*$");

再次古典 「正常*(特殊正常*)*」 模式)

函數體變爲:

function (value) { 
    regex = new RegExp("^[a-zA-Z0-9]+(?:-[a-zA-Z0-9]+)*$"); 
    return regex.test(value) && value.length >= 6; 
} 

編輯地:分組非捕獲因爲這裏沒有捕獲完成

1

在開始或結束時沒有破折號的限制使得正則表達式更加複雜一些。下面的正則表達式首先匹配單個字符,然後它可以選擇匹配零個或多個字符,包括短劃線,然後結束於非短劃線字符。

/^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?$/ 
+0

不,完全沒有:看看我的回答 – fge 2011-12-15 22:21:18

1

試試這個

regex = new RegExp("^(?!-)[a-z0-9-]*[a-z0-9]$", "i"); 

^錨字符串

(?!-)開始負前瞻確保字符串不以破折號

[a-z0-9-]* 0個或更多字符的類中開始

[a-z0-9]$以類別中的字符結尾

看到此regex here on Regexr

更新

這是使用兩個向前看符號的變體,這也將接受空字符串

^(?!-)(?!.*-$)[a-z0-9-]*$ 

See it on Regexr

更新2:最小6個字符

^(?!-)[a-z0-9-]{5,}[a-z0-9]$ 

See it on Regexr

爲了對付評論

它實際上是太複雜正則表達式 - 絕對速度低於 我正則表達式

我做了一個小的基準(在Perl,不該沒什麼大不了的)

sub WithLookahead($) { 
    my $string = shift; 

    return $string =~ /^(?!-)[a-z0-9-]*[a-z0-9]$/i; 
} 

sub WithOutLookahead($) { 
    my $string = shift; 

    return ($string =~ /^[a-zA-Z0-9]+(?:-[a-zA-Z0-9]+)*$/ 
      && length($string) >= 6); 
} 

sub BenchmarkLookahead($) { 
    use Benchmark; 
    my $testString = shift; 

    my $t0 = Benchmark->new; 
    for (0 .. 10000000) { 
     my $result = WithLookahead($testString); 
    } 
    my $t1 = Benchmark->new; 

    my $t2 = Benchmark->new; 
    for (0 .. 10000000) { 
     my $result = WithOutLookahead($testString); 
    } 
    my $t3 = Benchmark->new; 

    my $tdWith = timediff($t1, $t0); 
    my $tdWithOut = timediff($t3, $t2); 
    print "the code with Lookahead and test string \"$testString\" took:", timestr($tdWith), "\n"; 
    print "the code without Lookahead and test string \"$testString\" took:", timestr($tdWithOut), "\n"; 
} 

結果

與先行和測試字符串「富酒吧」的代碼把:16掛鐘秒(14.94 USR + 0.00 SYS = 14.94 CPU)
沒有先行和測試字符串「富酒吧」的代碼採用:18 wallclock secs(17.50 usr + 0.02 sys = 17.52 CPU)
帶Lookahead和測試字符串「-Foo-Bar」的代碼採用:13 wallclock秒(12.03 usr + 0.00 sys = 12.03 CPU)
代碼無Lookahead和測試字符串「-Foo-Bar」採用:14時鐘秒(13.44 usr + 0.00 sys = 13。44 CPU)
帶有Lookahead和測試字符串「Foo-Bar-」的代碼採用了:17 wallclock秒(15.28 usr + 0.00 sys = 15.28 CPU)
沒有Lookahead的代碼和測試字符串「Foo-Bar-」 23 wallclock secs(21.61 usr + 0.02 sys = 21.63 CPU)
Lookahead和測試字符串「Foo」的代碼採用:14 wallclock秒(13.70 usr + 0.00 sys = 13.70 CPU)
代碼沒有Lookahead和測試字符串「富」了:19掛鐘秒(17.09 USR + 0.02 = SYS 17.11 CPU)

所以,總體來說我與負向前查找正則表達式是不是一個簡單的正則表達式的組合更快結合一個外耳炎位l長度檢查。但是我需要調用每個代碼10000000次才能獲得顯着的結果,所以我不認爲它是一個使用哪個性能決策的決定。