简体   繁体   English

检查特殊字符和空格

[英]Checking for special characters and spaces

I have a hangman game created in java. 我有一个用java创建的刽子手游戏。 I want to create a simple function that will check if the word input has white space and/or special characters. 我想创建一个简单的函数来检查单词输入是否有空格和/或特殊字符。

I've found the functions String.replaceAll(), but I haven't been able to dig up a premade function that returns a boolean value for if there are special charactors and/or white space. 我找到了函数String.replaceAll(),但是我还没能找到一个premade函数,它返回一个布尔值,如果有特殊的charactors和/或空格。

Is there a function out there already? 那里有功能吗? Or at least a simpler way of specifying no white space or special characters other than doing the following? 或者至少是一种更简单的方法,除了执行以下操作之外,不指定空格或特殊字符?

public  void checkWord()
    {
        boolean flag = false;
        for(int i=0;i<wordArray.length;i++)
        {
            if(wordArray[i] == '1' || wordArray[i] == '2' || wordArray[i] == '3' || wordArray[i] == '4' || wordArray[i] == '5' || wordArray[i] == '6' || wordArray[i] == '7' || wordArray[i] == '8' || wordArray[i] == '9'  )
            {
                flag = true;
            }
        }
        if(flag == true)
        {
            System.out.println("Invalid characters used in the word");
            System.exit(0);
        }
    }

The function is getting dense, and I've only covered digits. 功能变得越来越密集,我只覆盖了数字。 Thoughts? 思考?

You can use a simple regular expression: 您可以使用简单的正则表达式:

public boolean isValidWord(String w) {
    return w.matches("[A-Za-z]*");
}

Explanation of the regex: 正则表达式的解释:

[A-Za-z] - capital or lowercase letter
*        - zero or more

More info on regexes: http://www.regular-expressions.info/ 关于正则表达式的更多信息: http//www.regular-expressions.info/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM