Reputation: 1468
I am new to regex going through the tutorial I found the regex [...]
says Matches any single character in brackets.
. So I tried
System.out.println(Pattern.matches("[...]","[l]"));
I also tried escaping brackets
System.out.println(Pattern.matches("[...]","\\[l\\]"));
But it gives me false
I expected true
because l
is inside brackets.
It would be helpful if anybody clear my doubts.
Upvotes: 6
Views: 1984
Reputation: 223
The tutorial is saying:
Matches any single character in brackets.
It means you replace ...
with a single character, for example [l]
These will print true:
System.out.println(Pattern.matches("[l]","l"));
System.out.println(Pattern.matches("[.]","."));
System.out.println(Pattern.matches("[.]*","."));
System.out.println(Pattern.matches("[.]*","......"));
System.out.println(Pattern.matches("[.]+","......"));
Upvotes: 2
Reputation: 24427
The tutorial is a little misleading, it says:
[...] Matches any single character in brackets.
However what it means is that the regex will match a single character against any of the characters inside the brackets. The ... means "insert characters you want to match here". So you need replace the ... with the characters that you want to match against.
For example, [AP]M
will match against "AM" and "PM".
If your regex is literally [...]
then it will match against a literal dot. Note there is no point repeating characters inside the brackets.
Upvotes: 4
Reputation: 96016
Characters that are inside [
and ]
(called a character class) are treated as a set of characters to choose from, except leading ^
which negates the result and -
which means range (if it's between two characters). Examples:
[-123]
matches -
, 1
, 2
or 3
[1-3]
matches a single digit in the range 1 to 3[^1-3]
matches any character except any of the digits in the range 1 to 3.
matches any character[.]
matches the dot .
If you want to match the string [l]
you should change your regex to:
System.out.println(Pattern.matches("...", "[l]"));
Now it prints true
.
The regex [...]
is equivalent to the regexes \.
and [.]
.
Upvotes: 4