lundi 15 février 2016

pattern.dotall is not working in between \Q and \E

I want to write a regular expression to fetch name and city from the input line.

example :

Hi David! how are you? are you in chennai now?

I need to fetch the david and chennai from this passage

I wrote the below code it is working fine but whenever there is line break in this line it is not working

package com.test;

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

public class Testing {

    public static void main(String[] args) {

        String input = "Passage : Hi David! how are you? are you in chennai now? "
                + "\n Hi Ram! how are you?\n are you in chennai now?";
        String regex1="\\QHi \\E(.*?)\\Q! how are you? are you in \\E(.*?)\\Q now?\\E";
        Pattern p = Pattern.compile(regex1,Pattern.DOTALL);
        Matcher m = p.matcher(input);

        StringBuffer result = new StringBuffer();
        while (m.find()) {
            m.appendReplacement(result,m.group(1)+" is fine and yes I am in "+m.group(2));
        }
         m.appendTail(result);
        System.out.println(result);
    }

}

Output :

Passage : David is fine and yes I am in chennai Hi Ram! how are you? are you in chennai now?

Expected Output

Passage : David is fine and yes I am in chennai Ram is fine and yes I am in chennai

Note : I have used Pattern.DOTALL also.

Thanks in advance!!!

Aucun commentaire:

Enregistrer un commentaire