2017-06-02 69 views
2

我不知道,爲什麼這個簡單的代碼不工作。我打算將字符串與允許的模式進行匹配。 該字符串應該只有a-z,A-Z,0-9,_(下劃線),.(點),-(hiphen)。只允許字符串中的某個字符。 Javascript

下面是代碼:

var profileIDPattern = /[a-zA-Z0-9_.-]./; 
var str = 'Heman%t'; 
console.log('hemant',profileIDPattern.test(str)); 

代碼日誌「真」下面的字符串,雖然這些字符串不匹配模式。

'Heman%t' -> true 
'#Hemant$' -> true 

我不知道是什麼問題。

回答

3

嘗試將其更改爲這個正則表達式(/^[a-zA-Z0-9_.-]*$/):

var profileIDPattern = /^[a-zA-Z0-9_.-]*$/; 
 
var str1 = 'Hemant-._67%' 
 
var str2 = 'Hemant-._67'; 
 
console.log('hemant1',profileIDPattern.test(str1)); 
 
console.log('hemant2',profileIDPattern.test(str2));

+0

嘿謝謝@ Arg0n,它的工作。你能幫忙嗎,這個*在這裏意味着什麼。如果我沒有錯,那麼^和$意味着字符串的開始和結束。我想,當我上次嘗試這種表達方式時,我沒有保留*。 –

+0

@HemantYadav它表示'[]'中的字符'零或多個'。如果你想'一個或多個'改爲'+'。你對'^'和'$'是正確的。 – Arg0n

+0

在你的模式中有一個缺陷,它也會匹配空字符串,試試'''.test(str1)' –

2

問題:[a-zA-Z0-9_.-]將任何字符匹配內部[].將經過這麼基本匹配任何它將匹配提字和任何其他字符

使用^$錨提開始和匹配的端,並刪除.

^[a-zA-Z0-9_.-]+:與任何給定值開始內部[]

[a-zA-Z0-9_.-]+$:一個或多個匹配和$結束比賽

var profileIDPattern = /^[a-zA-Z0-9_.-]+$/; 
 

 
console.log('hemant', profileIDPattern.test('Heman%t')); // no match - 
 
console.log('hemant-._', profileIDPattern.test('hemant-._')); // valid match 
 
console.log('empty',  profileIDPattern.test(''));   // no match ,empty