Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why dot inside square brackets doesn't match any character?

Tags:

java

regex

Why this [.]+ Java regular expression doesn't match my "foo" text, while .+ matches perfectly (tested here)?

like image 677
yegor256 Avatar asked Feb 28 '13 15:02

yegor256


People also ask

How do you escape square brackets in regex?

If you want to remove the [ or the ] , use the expression: "\\[|\\]" . The two backslashes escape the square bracket and the pipe is an "or".

How do I enable square brackets in regex?

Just make sure ] is the first character (or in this case, first after the ^ . result2 = Regex. Replace(result2, "[^][A-Za-z0-9/.,>#:\s]", "");

Do brackets need to be escaped in regex?

Although dot ( . ) has special meaning in regex, in a character class (square brackets) any characters except ^ , - , ] or \ is a literal, and do not require escape sequence.

Do square brackets need to be escaped?

Use square brackets as escape characters for the percent sign, the underscore, and the left bracket. The right bracket does not need an escape character; use it by itself. If you use the hyphen as a literal character, it must be the first character inside a set of square brackets.


1 Answers

[.] is equivalent to escaping the . (dot) character, i.e. \\..

Once the character appears in a character class, it loses its status as a special character.

As foo doesn't contain any dots, nothing is matched. .+, on the other hand, is a wildcard greedy expression that matches everything.

like image 171
Reimeus Avatar answered Oct 19 '22 09:10

Reimeus