tags:

views:

62

answers:

4

What is the regular expression for . and .. ?

if(key.matches(".")) {

do something 

}

The matches accepts String which asks for regular expression. Now i need to remove all DOT's inside my MAP.

+1  A: 

...

[.]{1}

or

[.]{2}

?

Noon Silk
+1  A: 

[+*?.] Most special characters have no meaning inside the square brackets. This expression matches any of +, *, ? or the dot.

Sachin Shanbhag
+6  A: 

. matches any character so needs escaping i.e. \., or \\. within a Java string (because \ itself has special meaning within Java strings.)

You can then use \.\. or \.{2} to match exactly 2 dots.

mikej
\. does not work with above code in key.matches
John
As mentioned, `\.` is the regular expression but to construct a String for this expression in Java you will need `\\.` because \ is used within Java strings for things like \n, \t etc. so \\ is needed for a literal \ within a String. Also, note that `String.matches` requires the regexp to match the **entire** String. If you want to do a substring search you will need to use `Matcher.find`
mikej
Also, can you clarify the requirements a bit. If you just need to check if the key contains a dot then you can use `key.contains` and don't really need a regexp at all.
mikej
+1  A: 

Use String.Replace() if you just want to replace the dots from string. Alternative would be to use Pattern-Matcher with StringBuilder, this gives you more flexibility as you can find groups that are between dots. If using the latter, i would recommend that you ignore empty entries with "\\.+".

public static int count(String str, String regex) {
    int i = 0;
    Pattern p = Pattern.compile(regex);
    Matcher m = p.matcher(str);
    while (m.find()) {
        m.group();
        i++;
    }
    return i;
}

public static void main(String[] args) {
    int i = 0, j = 0, k = 0;
    String str = "-.-..-...-.-.--..-k....k...k..k.k-.-";

    // this will just remove dots
    System.out.println(str.replaceAll("\\.", ""));
    // this will just remove sequences of ".." dots
    System.out.println(str.replaceAll("\\.{2}", ""));
    // this will just remove sequences of dots, and gets
    // multiple of dots as 1
    System.out.println(str.replaceAll("\\.+", ""));

    /* for this to be more obvious, consider following */
    System.out.println(count(str, "\\."));
    System.out.println(count(str, "\\.{2}"));
    System.out.println(count(str, "\\.+"));
}

The output will be:

--------kkkkk--
-.--.-.-.---kk.kk.k-.-
--------kkkkk--
21
7
11
Margus