grammar SwiftBlock;
@header {
package generated;
import java.util.Map;
import java.util.HashMap;
}
@lexer::header {
package generated;
}
@members {
HashMap message = new HashMap();
public Map<String,String> getMessage(){
return message;
}
}
message : block+;
block : '{' '1' ':' expr {System.out.println("expr1=" + $expr.text);} '}' |
'{' '2' ':' expr {System.out.println("expr2=" + $expr.text);} '}' |
'{' '3' ':' expr3* '}' |
'{' '4' ':' expr4+ '}' |
'{' '5' ':' expr5+ '}' ;
expr3 : '{' key ':' expr '}' {System.out.println("expr3=" + $expr3.text);message.put($key.text,$expr.text);} ;
expr4 : ('\n'|'\r')+ (':' key ':' expr {System.out.println("expr4=" + $expr.text); message.put($key.text,$expr.text);} | '-')+;
expr5 : ('\n'|'\r')+ '{' key ':' expr '}' {System.out.println("expr5=" + $expr.text);message.put($key.text,$expr.text);} ;
key : FIELDVALUE* {System.out.println("key=" + $key.text);} ;
expr : FIELDVALUE* {System.out.println("expr=" + $expr.text);} ;
/*------------------------------------------------------------------
* LEXER RULES
*------------------------------------------------------------------*/
FIELDVALUE : (~('-'|':'|'}'|'{'))+;
Compile grammar
java -cp /app/antlr-3.3/lib/antlr-3.3-complete.jar org.antlr.Tool -o generated SwiftBlock.g
Test program
import generated.SwiftBlockLexer;
import generated.SwiftBlockParser;
import java.io.FileInputStream;
import java.util.Map;
import org.antlr.runtime.ANTLRInputStream;
import org.antlr.runtime.CommonTokenStream;
public class AntlrSwiftBlock {
public static void main(String[] args) throws Exception {
FileInputStream fileInputStream = new FileInputStream("/home/dave/workspace/wls1033/testAntlr/src/swift.txt");
ANTLRInputStream input = new ANTLRInputStream(fileInputStream);
SwiftBlockLexer lexer = new SwiftBlockLexer(input);
CommonTokenStream tokens = new CommonTokenStream(lexer);
SwiftBlockParser parser = new SwiftBlockParser(tokens);
parser.message();
System.out.println("Message:");
for(Map.Entry<String,String> entry : parser.getMessage().entrySet()){
System.out.println(entry);
}
}
}
SWIFT message
{1:F01AAAABB99BSMK3513951576}{2:O9400934081223BBBBAA33XXXX03592332770812230834N}{3:{113:xxxx}{108:abcdefgh12345678}}{4:
:20:0112230000000890
:25:SAKG800030155USD
:28C:255/1
:60F:C011223USD175768,92
:61:0112201223CD110,92NDIVNONREF//08 IL053309
/GB/2542049/SHS/312,
:62F:C011021USD175879,84
-}{5:
{CHK:0F4E5614DD28}
{MAC:0F4E5614DD28}}
Result output
Message:
20=0112230000000890
62F=C011021USD175879,84
113=xxxx
CHK=0F4E5614DD28
108=abcdefgh12345678
25=SAKG800030155USD
MAC=0F4E5614DD28
60F=C011223USD175768,92
61=0112201223CD110,92NDIVNONREF//08 IL053309
/GB/2542049/SHS/312,
28C=255/1
No comments:
Post a Comment