简体   繁体   中英

Can't figure out why this regex doesn't work (multiple lines of text with “starts with” qualifier)

It's so hard to find out why this isn't working, my research indicates it should work. I'm try to do this logical match - start of line has from: then any amount of characters then start of line has sent: . Please see code, I would think it would print match found but doesn't:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test2 {
    public static void main(String[] args)
    {
        Pattern lineDividerGuessMatchPattern = Pattern.compile("(?m)(?i)(^from:)(.*?)(^sent:)");

        String testString = "cheese \n"
                + "from: cheese\n"
                + "sent: bacon";

        Matcher m = lineDividerGuessMatchPattern.matcher(testString);

        if(m.find())
            System.out.println("Match found");
    }
}

You need the (?s) flag too ( DOTALL mode) to make . match line terminators. This finds a match:

Pattern lineDividerGuessMatchPattern = 
    Pattern.compile("(?msi)(^from:)(.*?)(^sent:)");

I'm try to do this logical match - start of line has from: then any amount of characters then start of line has sent:

You should use (from:[^\\n]*\\nsent:)

Here is demo

Pattern explanation:

  (                    group and capture to \1:
    from:                'from:'
    [^\n]*               any character except: '\n' (newline) (0 or more times)
    \n                   '\n' (newline)
    sent:                'sent:'
  )                    end of \1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM