简体   繁体   English

检查“字符串”中是否包含其他值。 爪哇

[英]Check String for values other than those allowed. Java

I wrote a program that asks the use to input a string of 3 characters, which could be a combination of [a, b, v, ^]; 我编写了一个程序,要求使用该程序输入3个字符的字符串,该字符串可以是[a,b,v,^]的组合。

Here's what I have so far: 这是我到目前为止的内容:

do {
    System.out.print("Enter a two variable logical expression, no spaces: ");    // 'v' for or, '^' for and.
    expression = type.nextLine();
}
while ((expression.length() != 3) || !((expression.toUpperCase()).matches("[AB^V]")));

The loop is only suppose to continue when the string is not 3 characters long, or a character in the string is not allowed. 仅当字符串长度不超过3个字符或不允许字符串中的字符时才继续循环。

I entered a test string of: a^b, but the loop just keeps going. 我输入了一个测试字符串:a ^ b,但是循环一直在继续。

How do I fix this? 我该如何解决?

Thanks. 谢谢。

The correct regular expression is [AB^V]+ . 正确的正则表达式为[AB^V]+ Indeed the original expression would only match strings of length 1. 实际上,原始表达式只能匹配长度为1的字符串。

((expression.toUpperCase()).matches("[AB^V]+"))

^ does not need to be escaped, since it is between [ and ] (ie in a character class). ^不需要转义,因为它在[]之间(即在字符类中)。

Edit : actually ^ should be escaped if it was at the beginning of the character class (like in [\\\\^ABV]+ ), but not when it is preceded by other characters. 编辑 :实际上,如果^在字符类的开头(例如[\\\\^ABV]+ ),则应该转义,但在其他字符之后则不应转义。

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

相关问题 如何检查字符串中是否包含数字以外的其他字符? - how to check string contain any character other than number in java? java-检查字符串是否包含空格以外的任何其他字符 - java - check whether a string contains any characters other than spaces 不允许使用“ [xX] [mM] [lL]”。 -在字符串中创建XSLT文件 - “[xX][mM][lL]” is not allowed. - creating XSLT file within String Java检查另一个字符串中的一个字符串 - Java check one string in other string 检查字符串是否包含其他字符串Java的一部分 - Check if String contains part of other string Java checkstyle警告“不允许声明变量,返回值或'ArrayList'类型的参数。”是什么意思? - What does the checkstyle warning “Declaring variables, return values or parameters of type 'ArrayList' is not allowed.” mean? Java枚举:返回值不是String - Java enum: Return value other than String 除了'string [] args'之外,java的main方法中还有其他参数吗? - Is there any other parameter in the main method of java other than 'string[] args'? 我可以检查字符串中除特定字符之外的其他字符吗? - Can I check a String for characters other than specific ones? 如何检查字符串列表是否包含某个值以外的任何内容? - How to check if string list contains anything other than some value?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM