What is the meaning of regular expression [...]?

I'm new to regex passing through tutorial I found regex [...] says Matches any single character in brackets. . So I tried

 System.out.println(Pattern.matches("[...]","[l]")); 

I also tried to escape from brackets

 System.out.println(Pattern.matches("[...]","\\[l\\]")); 

But it gives me false I expected true because l is inside the brackets.

It would be helpful if someone cleared my doubts.

+6
source share
3 answers

The characters inside [ and ] (called the character class ) are considered as a set of characters to choose from, except for the leading ^ , which negates the result and - , which means a range (if it is between two characters). Examples:

  • [-123] matches - , 1 , 2 or 3
  • [1-3] matches one digit in the range of 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 must change your regex to:

 System.out.println(Pattern.matches("...", "[l]")); 

Now it prints true .

A regular expression [...] equivalent to regular expressions \. and [.] .

+4
source

The textbook is a little misleading, he says:

[...] Matches any character in brackets.

However, this means that the regular expression will match a single character against any of the characters inside the brackets. ... means "insert the characters you want to combine here . " So you need to replace ... with the characters you want to match.

For example, [AP]M will match "AM" and "PM".

If your regular expression is literally [...] , then it will match a literal point. Note that there are no duplicate characters in parentheses.

+4
source

The textbook says:

Matches any character in brackets.

This means that you replace ... with one character, for example [l]

They 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("[.]+","......")); 
+2
source

Source: https://habr.com/ru/post/986633/


All Articles