Dot behavior in regex patterns

前端 未结 4 354
一生所求
一生所求 2021-01-14 18:25
Pattern p2 = Pattern.compile(\".*\");
Matcher m2 = p2.matcher(\"true\");
System.out.println(m2.matches() + \" [\" + m2.group() + \"]\");

When I use

相关标签:
4条回答
  • 2021-01-14 18:33

    The dot . is a predefined character class. It matches any character (may or may not match line terminators). If want to define character class that includes a range of values, you can use [].

    0 讨论(0)
  • 2021-01-14 18:36

    [] is the character class and most inside it stand for their actual symbol. Dot in this case would just be a dot and not a dot with special meaning in regex.

    0 讨论(0)
  • 2021-01-14 18:48

    But I don't understand what is going on when I use this regexpr [.]*. It says me false.

    Because inside a character class, the dot loses its special meaning and will match a plain old dot (the . character).

    Outside of a character class the dot is a metacharacter that matches any character, excluding newlines (unless you use the Pattern.DOTALL modifier, of course).

    Or how to make a class of symbols with any characters without \n and \r.

    Use a negated character class:

     Pattern p2 = Pattern.compile("[^\\r\n]*");
    

    [^\r\n] means "match anything that's not a \r or a \n.

    0 讨论(0)
  • 2021-01-14 18:53

    .* means any character 0 or more times [.]* means dot character 0 or more times

    0 讨论(0)
提交回复
热议问题