Jay Donovan
Jay Donovan

Reputation: 25

C# / RegEx - Modify Lines in Text File

I have a large text file that I need to check line by line and modify accordingly. What I'm looking for is lines that start with DTP*348*D8*yyyymmdd (yyyymmdd will be populated with actual dates in the file). If the line falls between the lines REF*1L*0002 and REF*1L*0011 I want all dates prior to 20140601 to be changed to 20140601 (any dates later than 20140601 should be left alone). So DTP*348*D8*20090605 would become DTP*348*D8*20140601.

Lines between REF*1L*0011 and REF*1L*0030 I would like dates prior to 20140701 to be changed to 20140701 and anything later to be left alone. So DTP*348*D8*20140605 would become DTP*348*D8*20140701.

The line REF*1L*xxxx lines occur multiple times throughout the file, but they are not mixed up. For instance, once the first instance of REF*1L*0011 is reached, REF*1L*0002 will no longer appear in the file and once the line REF*1L*0030 is reached, neither REF*1L*0002 nor REF*1L*0011 will appear again in the file.

I just confused myself with all that. Hopefully it makes some sense!

EDIT: Here is an example of the file contents.

REF*1L*0002
REF*DX*100A
REF*ZZ*00
DTP*336*D8*19990816
NM1*IL*1*XXXX*XXXXX****34*XXXXXXXX
PER*IP**TE*XXXXXXXXXX
N3*XXXXX XXXXX XXX
N4*XXXXX*XX*XXXXX
DMG*D8*19760910*F*I
HD*030**HLT*0002XXX01*XXX
DTP*348*D8*20150601 (*This is the line I want to edit*)
INS*N*19*030**A
REF*0F*XXXXXX
REF*1L*0011

(The rest of the file contains lines similar to the above, repeating). The type of file I'm working with is called an EDI 834 if that helps.

Upvotes: 0

Views: 133

Answers (2)

dub stylee
dub stylee

Reputation: 3342

I am not proficient enough in regular expressions to try to help you achieve it that way, but since you said that is not a requirement, here is a .NET Fiddle that accomplishes what you are trying to do.

Basically, it loops through one line at a time, if it hits a line that begins with DTP*348 then it will parse out the date. If the date is less than 20140601, it will replace the date with 20140601.

The example just uses static text, but you can easily adapt the concept to reading in a text file and writing back to the text file.

Upvotes: 1

bubi
bubi

Reputation: 6491

About the date you can use this

File.WriteAllText(fn, Regex.Replace(File.ReadAllText(fn), 
    @"(201[0-3][0-9][0-9][0-9][0-9]|2014[0-6][0-9][0-9][0-9])", 
    "20140701"));

Not clear what is the range REF*1L*0011 to REF*1L*0030. If need to include all numbers from 0011 to 0030 the regular expression is

REF\*1L\*(001[1-9]|002[0-9]|0030)

Upvotes: 0

Related Questions