Pattern / Matcher in Java?

I have a specific text in Java and I want to use a template and matcher to extract something from it. This is my program:

public String getItemsByType(String text, String start, String end) {

    String patternHolder;
    StringBuffer itemLines = new StringBuffer();

    patternHolder = start + ".*" + end;

    Pattern pattern = Pattern.compile(patternHolder);
    Matcher matcher = pattern.matcher(text);

    while (matcher.find()) {
        itemLines.append(text.substring(matcher.start(), matcher.end())
                + "\n");

    return itemLines.toString();


This code works completely WHEN if the search text is on one line, for example:

String text = "My name is John and I am 18 years Old"; 

getItemsByType(text, "My", "John");


immediately extracts the text "My name is John" from the text. However, when my text looks like this:

String text = "My name\nis John\nand I'm\n18 years\nold"; 

getItemsByType(text, "My", "John"); 


This does not capture anything, as "Mine" and "John" are on different lines. How can I solve this?


source to share

2 answers

Use this instead:

Pattern.compile(patternHolder, Pattern.DOTALL);


From the javadoc, the flag DOTALL


Turns on dotall mode.

In the mode hitherto, expression. matches any character, including the line terminator. By default, this expression does not match line terminators.



Use Pattern.compile(patternHolder, Pattern.DOTALL)

to compile the template. Thus, the point will correspond to the new line. By default, newline is treated in a special way and does not match point.