2011-09-15 24 views
3

爲什麼String.matches返回true當兩個值在[]括號?爲什麼Java正則表達式「。* [two]。*」匹配「一個」?

System.out.println("[one]".matches("(?i).*" + "[two]" + ".*")); 
    //Why does it return true? Shouldn't "[]" be treated as value? 
System.out.println("one".matches("(?i).*" + "two" + ".*"));//OK - prints false 

System.out.println("[one]".equals("[two]"));//OK - prints false 
System.out.println("one".equals("two"));//OK - prints false 
+2

'[]'表示一個正則表達式的內部的字符類。由於您使用接受正則表達式的'matches()'方法,所以它們被解釋爲。嘗試在它們前面添加\ –

回答

1
Regex: .*  [two]  .* 
Match: "["  "o" "ne]" 

矩形括號必須加引號。

嘗試用"[one]".matches("(?i).*" + Pattern.quote("[two]") + ".*")代替。

9

Beacuase [two]匹配的字母t的一,W或O,其是字符串中"[one]"

6
System.out.println("[one]".matches("(?i).*[two].*")); 

打印true因爲character class[two]o匹配oneo。以下.*比賽ne - Voilà,成功比賽!

在正則表達式中,[abc]的意思是「字符a,bc之一」。

System.out.println("[one]".matches("(?i).*\\[two].*")); 

將打印false因爲現在的括號字面上處理。不過,這個正則表達式很有意義。

1

[two]匹配的方括號中的字母中的一個,即't', 'w', and 'o'
是爲了匹配的方括號,則需要轉義像\[two\]

相關問題