Why does String.matches
return true
when two values are in []
brackets?
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
Beacuase [two]
matches one of the letters t, w or o which is in the string "[one]"
System.out.println("[one]".matches("(?i).*[two].*"));
prints true
because the o
of the character class [two]
matches the o
in one
. The following .*
matches ne
- Voilà, successful match!
In a regular expression, [abc]
means "one of the characters a
, b
or c
".
System.out.println("[one]".matches("(?i).*\\[two].*"));
will print false
because now the brackets are treated literally. Not that this regex makes a lot of sense, though.
Regex: .* [two] .*
Match: "[" "o" "ne]"
The rectangular brackets have to be quoted.
Try "[one]".matches("(?i).*" + Pattern.quote("[two]") + ".*")
instead.
[two]
matches one of the letters in the square brackets, i.e. 't', 'w', and 'o'
To match the square brackets also, you need to escape it like \[two\]
精彩评论