Pattern/Matcher in Java?

Posted by user1007059 on Stack Overflow See other posts from Stack Overflow or by user1007059
Published on 2012-03-30T11:26:41Z Indexed on 2012/03/30 11:29 UTC
Read the original article Hit count: 321

Filed under:
|
|
|
|

I have a certain text in Java, and I want to use pattern 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 fully WHEN the searched text is on the same line, for instance:

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

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

immediately grabs the text "My name is John" out of 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"); 

It doesn't grab anything, since "My" and "John" are on different lines. How do I solve this?

© Stack Overflow or respective owner

Related posts about java

Related posts about regex