-3

Possible Duplicate:
regular expression for DOT

Say I have a String:

String domain =  "www.example.com";

To extract the word "example" I am using the split function in java

String[] keys = domain.split(".");
String result = keys[1];

Clearly this is wrong because the "." is a wrong regular expression since it matches any character.

What is the escape sequence which matches specifically the character "."?

Though this question does seem trivial but I can't seem to find any quick reference or previous answers. Thanks.

Community
  • 1
  • 1
spiritusozeans
  • 662
  • 1
  • 7
  • 13
  • 1
    possible duplicate of [regular expression for DOT](http://stackoverflow.com/questions/3862479/regular-expression-for-dot). Also, [similar](http://stackoverflow.com/questions/6122675/how-do-you-write-a-regular-expression-that-allows-the-special-character-dot) and [similar](http://stackoverflow.com/questions/3674930/java-regex-meta-character-and-ordinary-dot). – Mac Jun 12 '12 at 07:59
  • 1
    Maybe you want to read some basics: [What absolutely every Programmer should know about regular expressions](http://wp.me/p2pTzU-4) – stema Jun 12 '12 at 08:16

6 Answers6

7

By escaping it like as follows

\\.
jmj
  • 237,923
  • 42
  • 401
  • 438
  • Should we say that in regex, the `.` is escaped as `\.`; but as in Java `\ ` is a special character (to escape, ironically), it needs to be escaped as well - hence `\\.` – amaidment Jun 12 '12 at 08:00
4

Use \\.. You need to escape it.

RanRag
  • 48,359
  • 38
  • 114
  • 167
2

You can escape . by prefixing it with \\. Hence, use \\. Reason is that the literal string \\ is a single backslash. In regular expressions, the backslash is also an escape character. The regular expression \\ matches a single backslash.

Kazekage Gaara
  • 14,972
  • 14
  • 61
  • 108
2

You can get the regular expression for any literal string by using Pattern.quote().

Pattern.quote(".") evaluates to "\\."

In this case it would probably be clearer just to use \\.

plasma147
  • 2,191
  • 21
  • 35
0

You can escape the . character by using \\. or using the brackets [.].

Hence your code becomes:

String[] keys = domain.split("\\."); // or domain.split("[.]");
String result = keys[1];
Alex
  • 25,147
  • 6
  • 59
  • 55
0

Or you could create a class containing the dot, without escaping:

[.]
Cylian
  • 10,970
  • 4
  • 42
  • 55