Home > Software engineering >  Regex to match string of characters except for the last four characters and carriage return line fee
Regex to match string of characters except for the last four characters and carriage return line fee

Time:11-05

String Example:

  • AFN/FMHABX983,.XXXXXX,,155650/FPON43531W078351,0/FCOADS,01/FCOATC,017167^M

I need a regex that will find /FCOATC,01

/FCOATC, is a fixed match

The values after the comma can be: 01,02,03,1,2,3

7176 is a CRC value and can be any 4 Alpha Num Characters.

I originally started with this regex (\/)FCOATC,[^\/|^\n]* But then realized that I also don't want it to match on the 4 character CRC value. But I'm struggling because the values after the comma can be 1 or 2 characters.

Note: I have the ^/ included because this FCOATC section might be followed by another section that would start with a /. For example:

  • AFN/FMHABX983,.XXXXXX,,155650/FPON43531W078351,0/FCOADS,01/FCOATC,01/FCOXYZ,17167^M

So I need it to take each instance into consideration.

Thank you for your help!

CodePudding user response:

You could change the capture group to what you want to keep, and match an optional zero followed by 1, 2 or 3. Note that if the delimiter of the pattern is not / you don't have to escape the forward slash.

\/(FCOATC,0?[123])

See a regex demo.

If there should be either 4 digits, or / or the end of the string, you could match those using an alternation | matching either one of the alternatives:

\/(FCOATC,0?[123])(?:\d{4}|\/|$)

See another regex demo.

  • Related