ACH Pattern Match in C#

Viewed 172

I'm working on an Automated CLearing House (ACH) application and I'm doing the file validations.

The first validation I need to validate that the ACH file has the correct pattern of record types.

The pattern is this:

    1 - File Record Header
    5 - Batch Record Header
    6 - Entry Detail Record
    7 - Addenda Record
    8 - Batch Control Record
    9 - File Control Record

The number is the record type or the first character of the line. The text describes the record type.

I want test that a file follows the above pattern..

Some variations including the following..

Addenda Record is not required

    1 - File Record Header
    5 - Batch Record Header
    6 - Entry Detail Record
    8 - Batch Control Record
    9 - File Control Record

File can have one or more batches..

1 - File Record Header
5 - Batch Record Header
6 - Entry Detail Record
7 - Addenda Record
8 - Batch Control Record
5 - Batch Record Header
6 - Entry Detail Record
7 - Addenda Record
8 - Batch Control Record
5 - Batch Record Header
6 - Entry Detail Record
7 - Addenda Record
8 - Batch Control Record
9 - File Control Record

The File Record Header must be at the top of the file so the following would fail...

5 - Batch Record Header
1 - File Record Header
6 - Entry Detail Record
7 - Addenda Record
8 - Batch Control Record
9 - File Control Record

Would RegEx be best for this? Any advice would be greatly appreciated.

2 Answers

It sounds, based on your description, like a job for a mini-DSL (Domain Specific Language). While RegEx would be a good start in terms of tokenizing the input, I think the rules may prove too complex for a regular language. I'd express the syntax using some sort of a Context-Free Grammar (CFG), and write a parser to ensure rules are properly followed. I would not rely solely on RegEx in this case.

You already have a very good defined set of rules for your DSL - turning it into lexical and syntactic grammars would be the next step. The approach is similar to that of a front-end part of a compiler - down to an Abstract Syntax Tree (AST), which you can then fully validate. There's just no back-end (optimization or code gen) - once you validate your parsed tree, you either have a syntax error (so, input rejected), or proper structure (so, input accepted).

You can leverage language recognition tools, such as ANTLR, to get going quicker.

I agree with CoolBots, however, if you do want a massive disgusting Regular Expression, this should work according to how I understand your requirements:

1 - File Record Header\n(5 - Batch Record Header\n6 - Entry Detail Record\n(7 - Addenda Record\n)?8 - Batch Control Record\n)+9 - File Control Record\n?

Here's a link to a regex tester with your examples: https://regexr.com/5a7ti

Related