检查字符串是否包含除以外的内容

时间:2017-09-11 15:33:04

标签: jquery regex validation

我有一个输入字段,我想验证并限制输入的字符。

如果字段包含除以下内容以外的任何内容,如何显示错误?

public static void main(String[] args){
    char whatnow = 'Y';
    Scanner scan = new Scanner(System.in);

    while (whatnow != 'N' && whatnow != 'n') {
        int choice = printMenuAndAsk(scan);

        if (choice == 99)
            break;
        else performOperation(choice, scan);

        System.out.println("Do you want to continue calculating? [Y/N]:"); 
        whatnow = scan.next().charAt(0);

        while(whatnow != 'N' && whatnow != 'Y' && whatnow != 'n' && whatnow != 'y') { 
            System.out.println("Incorrect answer");
            whatnow = scan.next().charAt(0);
        }
    }   
    scan.close();   
}

public static int printMenuAndAsk(Scanner scan) {
    int choice;

    System.out.println("Welcome to StemCalc Z Edition(Integers only)!");
    ...
    System.out.println("Enter your choice[1-4 or 99]:"); 
    choice = scan.nextInt();

    while ((choice < 1 || choice > 4) && choice != 99) {
        System.out.println("Please enter 1, 2, 3, 4, or 99: ");
        choice = scan.nextInt();
    }

    return choice;
}

public static void performOperation(int operation, Scanner scan) {
    System.out.println("Enter first:");
    int firstnumber = scan.nextInt();
    System.out.println("Enter second:");
    int secondnumber = scan.nextInt();

    if (choice == 1)
        System.out.println(firstnumber + " + " + secondnumber + " = " + (firstnumber+secondnumber));
    else if (choice == 2) 
        System.out.println(firstnumber + " - " + secondnumber + " = " + (firstnumber-secondnumber));
    else if (choice == 3) 
        System.out.println(firstnumber + " * " + secondnumber + " = " + (firstnumber*secondnumber));
    else if (choice == 4) {
        while (secondnumber == 0) {
            System.out.println("ERROR-CANNOT DIVIDE TO ZERO! Type another integer:");
            secondnumber = scan.nextInt();
        }
        System.out.println(firstnumber + " / " + secondnumber + " = " + (firstnumber/secondnumber));
    }
}

我尝试过使用

a-z
A-Z
0 to 9
!$%&*:;#~@

但这似乎不起作用。有什么想法吗?

由于

1 个答案:

答案 0 :(得分:2)

引用我的评论,您可以使用以下任一方法来捕获您所呈现的列表中没有的任何字符。

a-z
A-Z
0 to 9
!$%&*:;#~@
[^a-zA-Z0-9!$%&*:;#~@]

点击here查看其实际效果。我做了一些键盘粉碎,正如你所看到的,它抓住了列表中没有的字符。

如果您想使用( regex here )在上面的正则表达式中向用户显示错误,并且如果您的匹配项大于0,请拒绝该条目。

根据regex101上生成的代码(在提供的外部链接中),您可以使用以下代码对其进行测试。

const regex = /([^a-zA-Z0-9!$%&*:;#~@])/g;
const str = `afdskljfalsfhaljsf jdsalfhajslfjdsf haskjlfjdskfa sdfl;dasj fas kjdfs2345tg!@*%(&)&^%\$@#@!!\$%^&%(\$%\$##@\$@>?"{P}P@#!é45049sgfg~~~\`\`\`j;fad;fadsfafds
{":

    fd
:"L'KM"JNH¨MJ'KJ¨HN'GFDMG`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }

    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}

在上面的代码中,任何匹配都会在最后forEach块中捕获并输出到控制台。如果匹配发生,您可以使用if语句来输出错误。请查看Check whether a string matches a regex,这篇文章解释了如何测试匹配

  

如果您想要的只是一个布尔结果,请使用regex.test()

/^([a-z0-9]{5,})$/.test('abc1');   // false

/^([a-z0-9]{5,})$/.test('abc12');   // true

/^([a-z0-9]{5,})$/.test('abc123');   // true
     

...您可以从正则表达式中删除(),因为您不需要   捕获。

相关问题