只允许字符串中的某个字符。使用Javascript

时间:2017-06-02 12:09:28

标签: javascript regex pattern-matching

我不知道,为什么这个简单的代码不起作用。我打算将字符串与允许的模式匹配。 字符串应仅包含a-zA-Z0-9_(下划线),.(点),-(hiphen)。

以下是代码:

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

代码记录下面字符串的'true',尽管这些字符串与模式不匹配。

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

我不知道是什么问题。

2 个答案:

答案 0 :(得分:3)

尝试将其更改为此RegExp(/^[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));




答案 1 :(得分: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




相关问题