2014-11-22 133 views
0

我有這個無功能的javascript:匹配字母字符正則表達式變量只

function test(id) { 
    if (id.match('^(.+?)#')) { 
     alert(RegExp.$1); 
    } 
} 

test('test#f'); // should alert 'test' 
test('tes4t#f'); // should not alert 

http://jsfiddle.net/r7mky2y9/1/

我只想匹配#之前出現a-zA-Z字符。我嘗試調整正則表達式,因此它是(.+?)[a-zA-Z],但我有一種不正確的感覺。

回答

2

這是正則表達式101爲您:

var m = id.match(/^([a-zA-Z]+)#/); 
if (m) alert(m[1]); 

在Javascript中,正則表達式斜線之間定義。

此外,懶惰量詞在這裏沒有用。我沒有測試演出,但不應該有任何區別。

最後,利用返回值match的優勢,該值返回並使用完整的mathe表達式排列,然後是捕獲的組。

+0

我看過正則表達式沒有使用斜槓,它們是強制還是它們有某種目的? – 2014-11-22 01:10:26

+1

@OP也許你已經在PHP中看到過它們,而不是在Javascript中。 – MaxArt 2014-11-22 01:10:51

+0

表達式[a-zA-Z]被稱爲[字符類](http://www.regular-expressions.info/charclass.html)。 – DavidRR 2014-11-22 03:00:37

1

試試這個:

function test(id) { 
    var rmatch = /^([a-zA-Z]+?)#/; 
    var match = id.match(rmatch); 
    if (match) { 
    alert(match[1]); 
    } 
} 

說明:

function test(id) { 
    var rmatch = /^([a-zA-Z]+?)#/; // This constructs a regex, notice it is NOT a string literal 
    // Gets the match followed by the various capture groups, or null if no match was found 
    var match = id.match(rmatch); 
    if (match) { 
    // match[1] is the first capture group, alert that 
    alert(match[1]); 
    } 
} 
0

使用if(id.match(/^([a-zA-Z]+)#/))

更新了我的答案,因爲match需要一個regex參數,而不是一個字符串。由於某些原因,id.match(/^([A-z]+)#/)^test匹配。爲什麼?

+0

這是downvoted - 這個表達不正確?我測試了它,它似乎檢查出好嗎? – 2014-11-22 01:15:51

0

試試這個:

function test(id) { 
    var regex = /([a-z]+)#/i, 
     group = regex.exec(id); 
    if (group && group[1]) { 
    alert(group[1]); 
    } 
} 

它的說法捕捉(用括號)一組的一個或多個字母(即[az] +),其次是哈希,並匹配不區分大小寫(因爲我在最後)。

相關問題