java Java检测字符串中的特殊字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10902911/
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 03:02:25  来源:igfitidea点击:

Java detect special characters in a string

javaregexspecial-characters

提问by Eric

I use regex

我使用正则表达式

r="[^A-Za-z0-9]+"; 

to detect if a string has one or more chars other than letters and digits;

检测一个字符串是否有一个或多个字母和数字以外的字符;

Then I tried the following:

然后我尝试了以下方法:

Pattern.compile(r).matcher(p).find();

I tested:

我测试过:

! @ # $ % ^ & * ( ) +  =- [ ] \ ' ; , . / { } | " : < > ? ~ _ `

Most of the time, it works except backsplash \ and caret ^.

大多数情况下,除了反斜杠 \ 和插入符号 ^ 外,它都可以工作。

e.g.

例如

String p = "abcAsd10^"    (return false)
String p = "abcAsd10\"   (return false) 

Anything I miss?

我有什么想念的吗?

回答by jahroy

The following code prints "Found: true" when I compile and run it:

当我编译并运行它时,以下代码打印“Found:true”:

class T
{
    public static void main (String [] args)
    {
        String thePattern = "[^A-Za-z0-9]+"; 
        String theInput = "abskKel35^";
        boolean isFound = Pattern.compile(thePattern).matcher(theInput).find();
        System.out.println("Found: " + isFound);
    }
}

Not sure why you would see a different result...

不知道为什么你会看到不同的结果......

回答by baby boom

When I run this code on my machine it prints true..

当我在我的机器上运行此代码时,它会打印 true..

        String r="[^A-Za-z0-9]+"; 
        String p = "abcAsd10\" ;
        Matcher m = Pattern.compile(r).matcher(p);
        System.out.println(m.find());

true

真的

回答by buckley

Shouldn't that be:

不应该是:

r="[^A-Za-z0-9]+"; 

In your question you write a_z (underscore)

在你的问题中你写 a_z (下划线)

回答by Paul Vargas

You could also change only:

您也可以只更改:

[\w&&^_]+

Where:

在哪里:

  • \wA word character with underscore: [a-zA-Z_0-9]
  • \WA non-word character: [^\w]
  • \w带下划线的单词字符: [a-zA-Z_0-9]
  • \W一个非单词字符: [^\w]

See more in class Pattern

在课堂上查看更多 Pattern

回答by Robert de W

Try quoting your input into the matcher.

尝试将您的输入引用到匹配器中。

Pattern.quote(p)

回答by Eric

Sorry, I had

对不起,我有

r="[^A-za-z0-9]+"; (with little "z", i.e. A-z). 

That causes returning "false". But why it works with other special chars except backsplash \ and caret ^?

这会导致返回“false”。但是为什么它可以与除反斜杠 \ 和插入符号 ^ 之外的其他特殊字符一起使用?

回答by elias

Simply do:

简单地做:

p.matches(".*\W.*"); //return true if contains one or more special character