javaregex

extract line that begin with a given pattern in java


I have a multi-line text and I just want to extract the whole line that begin with a given pattern. For exemple, I have this bloc of text

v=0
o=Z 0 0 IN IP4 127.0.0.1
s=Z
c=IN IP4 127.0.0.1
t=0 0
m=audio 8000 RTP/AVP 3 110 8 0 98 101
a=rtpmap:110 speex/8000
a=rtpmap:98 iLBC/8000
a=fmtp:98 mode=20
a=rtpmap:101 telephone-event/8000
a=fmtp:101 0-15
a=sendrecv

And I want to extract the line : c=IN IP4 127.0.0.1 by using the pattern prefix c=IN

It is possible ?


Solution

  • Yes, you can do it with pattern c=IN.*, where .* is all the characters till the end of the line, and the Matcher like:

    String ttt = "v=0\n" +
                    "o=Z 0 0 IN IP4 127.0.0.1\n" +
                    "s=Z\n" +
                    "c=IN IP4 127.0.0.1\n" +
                    "t=0 0\n" +
                    "m=audio 8000 RTP/AVP 3 110 8 0 98 101\n" +
                    "a=rtpmap:110 speex/8000\n" +
                    "a=rtpmap:98 iLBC/8000\n" +
                    "a=fmtp:98 mode=20\n" +
                    "a=rtpmap:101 telephone-event/8000\n" +
                    "a=fmtp:101 0-15\n" +
                    "a=sendrecv";
    
    Pattern pattern = Pattern.compile("c=IN.*");
    Matcher matcher = pattern.matcher(ttt);
    if (matcher.find())
         System.out.println(matcher.group());
    

    Or you can split it by \n into an array of the lines and iterate over this array, until you get the one, which starts with c=IN.