开发者

Compare data with Regular Expression

I have some data (E.g.: 'acs24','45开发者_运维技巧','ds' etc). Using this data I have the following method

function formatData(data) {
    var rege = /^([A-Za-z0-9_\-\.])$/;
    if ( rege.test(data) ) {
        alert('Alpaha Numeric data');
    }
}

But this is not working. What is wrong with this function?


Because it matches only one character and have an invalid range. If you want to allow hyphens, it need to be the last character in the regular expression list, otherwise it'll fail as _-. is an invalid range.

var rege = /^[A-Za-z0-9_.-]+$/;

Edit: Well, I pointed it before you've changed the question. :P


Because it matches only one character.

var rege = /^([A-Za-z0-9_\-\.]+)$/;

This one matches at least one character.

Extra detail: The parentheses are not necessary here. They don't harm though.


The following link has the anser

Anyway the answer is

"^[a-zA-Z0-9_]+$"

Your Regex would search for only 1 character ...


use + to match one or more characters

function formatData(data) {
    var rege = /^([A-Za-z0-9_\-\.])+$/;
    if ( rege.test(data) ) {
        alert('Alpaha Numeric data');
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜