检查字符串是否包含除句点和问号之外的特殊字符 Java

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12906586/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 10:44:16  来源:igfitidea点击:

Check if a string contains special characters except period and question mark Java

java

提问by NateSHolland

I'm trying to find a way to use regex and match to see if a string contains a special character with the exception of a period or comma. I'm not very familiar with regex and about to bang my head on a wall. What is the regex to when I call

我试图找到一种方法来使用正则表达式和匹配来查看字符串是否包含特殊字符(句点或逗号除外)。我对正则表达式不是很熟悉,正准备把头撞到墙上。我打电话时的正则表达式是什么

string.matches("??????");

will return a boolean based on whether string contains a special character other than a period or comma?

将根据字符串是否包含句点或逗号以外的特殊字符返回一个布尔值?

回答by ruakh

You can write:

你可以写:

string.matches("[a-zA-Z.? ]*")

That will evaluate to trueif every character in the string is either a lowercase letter a-z, an uppercase letter A-Z, a period, a question mark, or a space. (And to falseotherwise, of course.)

这将评估true字符串中的每个字符是否是小写字母a-z、大写字母A-Z、句点、问号或空格。(false当然,否则。)