正则表达式验证单次出现的字符

时间:2011-06-17 07:25:43

标签: javascript regex

我想检查输入字符串以验证正确的文本。验证将使用javascript完成,现在我正在使用此代码:

keychar = String.fromCharCode(keynum);
var text = txtBox.value + keychar;
textcheck = /(?!.*(.)\1{1})^[fenFN,]*$/;
return textcheck.test(text);

允许使用的字符串例如:
˚F
Ë
F,E
N,F,E,F,N

不允许的例子:
FF
FE
F,F
楼EE
F,E,N,F
n ,,(虽然这可能没事)

这可以用Javascript中的正则表达式来解决吗?

2 个答案:

答案 0 :(得分:3)

虽然可以使用正则表达式,但它产生了一个相当大的正则表达式,可能很难理解(并因此维护)。我会选择Benjam建议的“手动”选项。

然而,使用正则表达式,可以这样做:

var tests = [
  'f',
  'e',
  'f,e',
  'n,f,e,F,N',
  'ff',
  'fe',
  'f,f',
  'f,ee',
  'f,e,n,f',
  'n,,',
  'f,e,e'
];

for(var i = 0; i < tests.length; i++) {
  var t = tests[i];
  print(t + ' -> ' + (t.match(/^([a-zA-Z])(?!.*\1)(,([a-zA-Z])(?!.*\3))*$/) ? 'pass' : 'fail'));
}

将打印:

f -> pass
e -> pass
f,e -> pass
n,f,e,F,N -> pass
ff -> fail
fe -> fail
f,f -> fail
f,ee -> fail
f,e,n,f -> fail
n,, -> fail
f,e,e -> fail
正如您在Ideone上看到的那样

一个小小的解释:

^                     # match the start of the input
([a-zA-Z])            # match a single ascii letter and store it in group 1
(?!.*\1)              # make sure there's no character ahead of it that matches what is inside group 1
(                     # open group 2
  ,([a-zA-Z])(?!.*\3) #   match a comma followed by a single ascii letter (in group 3) that is not repeated
)*                    # close group 2 and repeat it zero or more times
$                     # match the endof the input

答案 1 :(得分:2)

我不认为你可以单独使用regexp,因为他们不太擅长在文本中查找重复项。我确信它可以完成,但它根本不会很好。

您可能想要做的是逐个字符地解析字符串并将当前字符存储在数组中,并在解析字符串时,检查是否已使用该字符,如下所示:

function test_text(string) {
    // split the string into individual pieces
    var arr = string.split(',');
    var used = [];

    // look through the string for duplicates
    var idx;
    for (idx in arr) {
        // check for duplicate letters
        if (used.indexOf(arr[idx])) {
            return false;
        }

        // check for letters that did not have a comma between
        if (1 < arr[idx].length) {
            return false;
        }

        used.push(arr[idx]);
    }

    return true;
}

您可能还希望通过在某处包含此脚本来确保您运行此浏览器的浏览器支持Array.indexOf:Mozilla indexOf