Search code examples
javaregexedi

Regular Expression for EDI file


I want to get a value in a edi file having below format

\nRJCK3:0*20180105*U*127.35
\nRJCK3:0*20180105*B*127.35 

I want a value U in 1st case, which comes between 2nd & 3rd star after RJC*K3, and want B in second string

Precisely, want to fetch a single character from a string, where that character will comes between 2nd & 3rd star(*) of a RJC*K3(static value).


Solution

  • You can use a classic Pattern matching way :

    String str1 = "\\nRJC*K3:0*20180105*U*127.35";
    Matcher m = Pattern.compile("RJC\\*K3.*\\*(\\w)\\*.*").matcher(str1);
    String res1 = m.find() ? m.group(1) : "";
    System.out.println(res1);       // U
    

    But if there is always the same amount of * before the letter you want, you cn easily split and take the 3rd part :

    String str2 = "\\nRJC*K3:0*20180105*G*127.35";
    String res2 = str2.split("\\*")[3];
    System.out.println(res2);        // G