2017-02-07 23 views
1

我試圖編碼以這樣的方式,碼不工作正則表達式來檢查前兩個字符必須是「1(numaric) - 」 9字母的單詞remaing應alphanumaric

var redEx = /^1-[0-9a-zA-Z]{7}/; 

document.getElementById("rowidOpty").value.test(redEx) 

示例:「1-5S6AW2R ':在字符串中,第一個字母應該是數字,第二個字符必須是「 - 」,並保持字母數字。

+1

加上'$''錨/^1- [0-9A-ZA-Z] {7} $ /'和語法錯誤'regex.test(值)' – Tushar

+2

*什麼*不工作,什麼是T他爲什麼輸入了你意想不到的結果? – Bergi

+0

在這種情況下:document.getElementById(「rowidOpty」)。value.match(redEx) –

回答

1

這是regexObj.test(string)而不是string.test(regexObj)

有關更多信息,請參閱RegExp.prototype.test()

console.log(/^1-[0-9a-zA-Z]{7}/.test('1-5S6AW2R'))

0

pattern = /^[0-9]-(\w+)/g; 
 

 
console.log('1-5S6AW2R'.match(pattern))

嘗試這種模式​​

Demo Regex

+1

'{1}'是無用的;-) – laruiss

+1

'\ w'匹配'[a-zA-Z0-9_]',所以它與[a-zA-Z0-9]不一樣。 '。 –

0

你有錯誤的函數語法:

regexp.test([str]) 

,右邊是:

var regEx = /^1-[0-9a-zA-Z]{7}/; 
 
var string = '1-5S6AW2R'; 
 

 
console.log(regEx.test(string));

+0

在這種情況下:document.getElementById(「rowidOpty」).value.match(redEx) –

0

如果你想驗證輸入只有一個數字,一個破折號和7相匹配字母數字,請使用:

/^[0-9]-[a-zA-Z-0-9]{7}$/; 

,或者如果第一隻能是數字1:

/^1-[a-zA-Z-0-9]{7}$/; 

如果你要搜索的字符串,這個模式所有出現含有大量的文字:

/(^|\s)[0-9]-[a-zA-Z-0-9]{7}(\s|$)/g; 

var restrictivePattern = /^[0-9]-[a-zA-Z-0-9]{7}$/; 
 
var loosePattern = /(^|\s)[0-9]-[a-zA-Z-0-9]{7}(\s|$)/g; 
 
var str = '1-A78Z2TE'; 
 
var longStr = 'We have 2 different codes 1-AYRJ3F4 and 4-23RJ3F4'; 
 

 
console.log("Validation of string to match pattern: ", str.match(restrictivePattern)) 
 
console.log("Multiple matches in string: ", longStr.match(loosePattern))

相關問題