Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I cannot match a String containing newlines when the newline is obtained by using %n in Formatter object or String.format(). Please have a look at the following program:

public class RegExTest {

  public static void main(String[] args) {
    String input1 = String.format("Hallo
next line");
    String input2 = String.format("Hallo%nnext line");
    String pattern = ".*[

].*";
    System.out.println(input1+": "+input1.matches(pattern));
    System.out.println(input2+": "+input2.matches(pattern));
  }

}

and its output:

Hallo
next line: true
Hallo
next line: false

What is going on here? Why doesn't the second string match?

Java version is 1.6.0_21.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
405 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can set the Pattern.DOTALL flag to make . match newlines, as default it doesn't. It is done with the (?s) notation. So, this regex does what you want:

    String pattern = "(?s).*[

].*";

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...