简体   繁体   中英

Java Regular Expression Multiline

I'm trying to get the result of a match with two lines and more, this is my text in a file (for JOURNAL ENTRIES for Wincor ATM):

DEMANDE SOLDE
N° CARTE  : 1500000001180006
OPERATION NO.  : 585068
========================================
RETRAIT
N° CARTE   1600001002200006
OPERATION NO.  : 585302
MONTANT   :  MAD 200.00
========================================
... etc.

Theare more lines repeated for each operation : retrait(ATMs), demande de solde (balance inquiry), which I want to get a resul like: RETRAIT\\nN° CARTE 1600001002200006 My java code:

String filename="20140604.jrn";
File file=new File(filename);
String regexe = ".*RETRAIT^\r\n.*CARTE.*\\d{16}"; // Work with .*CARTE.*\\d{16}: result: N° CARTE  :      1500000001180006 N° CARTE         1600001002200006
Pattern pattern = Pattern.compile(regexe,Pattern.MULTILINE);
try {
    BufferedReader in = new BufferedReader(new FileReader(file));
while (in.ready()) {
    String s = in.readLine();
    Matcher matcher = pattern.matcher(s);

    while (matcher.find()) {     // find the next match           
         System.out.println("found the pattern \"" + matcher.group());          
      }
    }
        in.close();        
    }        
    catch(IOException e) {
        System.out.println("File 20140604.jrn not found");
    }

Any Solution Please ?

I am unable to test this right now, but it looks like you have the boundary special character '^' in the wrong spot. It is trying to match RETRAIT followed by the beginning of a line followed by newline characters, when the beginning of the line won't start until after the newline characters.

UPDATE: With an online java regex tool, I've been able to test this:

^RETRAIT\s*\w+.*CARTE\s+\d{16}

which matches what you want in multiline mode. The \\s special character consumes whitespace (including carriage return and new line), which is more resilient than checking explicitly for \\n or \\r.

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