正则(.)*和[.]*
的区别

解决方案 »

  1.   

    放到metacharacter中的和在外部很多是有区别的。比如.在外部的时候是匹配任意字符,但是在[]里却是匹配一个点
      

  2.   

    小括号表示一个组,它可以是一个字符,也可以是多个字符,如(a|b|c|d)意思就是a或b或c或d任意一个,(abc|like|love)则是表示abc或like或love任意一个。中括号表示只表示一个字符的可选范围,如[a-z]表示这个字符可以是所有小写字符。
      

  3.   

    应该是这个意思,元字符.放在[]中是匹配一个.放在()中则是匹配任意字符。搞的我迷惑。
    找了个例子:import java.io.Console;
    import java.util.regex.Pattern;
    import java.util.regex.Matcher;public class RegexTestHarness { public static void main(String[] args) {
    Console console = System.console();
    if (console == null) {
    System.err.println("No console.");
    System.exit(1);
    }

    while (true) {
    Pattern pattern = Pattern.compile(console.readLine("%nEnter your regex: "));
    Matcher matcher = pattern.matcher(console.readLine("Enter input string to search: "));
    boolean found = false;
    while (matcher.find()) {
    console.format("I found the text \"%s\" starting at index %d " +
    "and ending at index %d.%n",
    matcher.group(), matcher.start(), matcher.end());
    found = true;
    }
    if (!found) {
    console.format("No match found.%n");
    }
    }
    }
    }out:

    Enter your regex: (.)*
    Enter input string to search: ddd
    I found the text "ddd" starting at index 0 and ending at index 3.
    I found the text "" starting at index 3 and ending at index 3.Enter your regex: [.]*
    Enter input string to search: ddd
    I found the text "" starting at index 0 and ending at index 0.
    I found the text "" starting at index 1 and ending at index 1.
    I found the text "" starting at index 2 and ending at index 2.
    I found the text "" starting at index 3 and ending at index 3.