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

4

我使用正则表达式。

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

检测字符串中是否包含字母和数字以外的字符;

然后我尝试了以下方法:

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

我进行了测试:

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

大多数情况下,它可以正常工作,除了反斜杠\和插入符号^。
例如:
String p = "abcAsd10^"    (return false)
String p = "abcAsd10\\"   (return false) 

Anything I miss?


我得到了"abcAsd10\"和"abcAsd10^"的匹配,所以它返回true。请注意,我使用的是C#,因此我认为它与Java有关。如果您编写一个小的代码示例来演示您的问题,那么它可能会有所帮助。 - buckley
就此而言,在 Ideone 上,这两个字符串似乎是匹配的 [http://ideone.com/KmWPk]。 - eldarerathis
抱歉,我的代码中有一个小写字母 z 的正则表达式 r="[^A-za-z0-9]+"。这会导致返回 "false"。 - Eric
你现在有答案了吗?不清楚你的问题是打错字还是问题本身。 - buckley
我在我的代码中使用了 r="[^A-za-z0-9]+" (其中小写字母 "z",即 A-z)。这会导致返回 "false"。但是为什么它可以处理除反斜杠 \ 和插入符号 ^ 之外的其他特殊字符呢? - Eric
7个回答

2
以下代码在编译和运行时将打印“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);
    }
}

不确定为什么您会看到不同的结果...

涉及IT技术,请确认是否需要更准确的翻译。

1

这不应该是这样吗:

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

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


1

您也可以仅更改:

[\w&&^_]+

说明:

  • \w 一个带下划线的单词字符:[a-zA-Z_0-9]
  • \W 一个非单词字符:[^\w]

更多信息请参见 Pattern 类。


也许尝试另一种方式会很有趣。 - Paul Vargas

1
当我在我的机器上运行这段代码时,它会输出 true。
        String r="[^A-Za-z0-9]+"; 
        String p = "abcAsd10\\" ;
        Matcher m = Pattern.compile(r).matcher(p);
        System.out.println(m.find());


最初他有 [^A-Za_z0-9]+ - Paul Vargas
所以我们需要标记这个问题...它只是一个 bug。 - baby boom
原始的正则表达式([^A-Za_z0-9]+)应该返回true,Paul。有人尝试过“[^A-Za_z0-9]+”吗? - Eric

0

抱歉,我有

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

这会导致返回“false”。但是为什么它可以处理除反斜杠\和脱字符^之外的其他特殊字符呢?


0

只需这样做:

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

0
尝试将您的输入引用到匹配器中。
Pattern.quote(p)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接