Regex to match string of characters except for the last four characters and carriage return line feed

Viewed 61

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.

Edited to add the following: To break out the /FMH portion I have a dilemma there as well. The breakout for that section is as follows:

Fixed Match /FMH 
1-7 alpha numeric characters 
Fixed Match , 
7 [.0-9A-Z-] characters 
Optional Fixed Match , 
Optional 6 characters 
Optional Fixed Match , 
Optional 6 digits

All of that could be followed by a / or a 4 character CRC code that would be followed by a carriage return line feed. I want to grab everything listed above, excluding the / or 4 character CRC that could follow.

Examples: /FMHABX983,.XXXXXX,,155650/ /FMHABX983,.XXXXXX/ /FMHAMX022,.XXXXXX,A07176,003555/ /FMHAMX022,.XXXXXX,A071761234\r\n /FMHABX983,.XXXXXX1234\r\n /FMHABX983,.XXXXXX,,1556501234\r\n /FMHABX983,.XXXXXX,,1234\r\n /FMHABX983,.XXXXXX,1234\r\n

Thank you for your help!

1 Answers

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.

Edit

You can optionally match all the parts in between, and at the end match either / or 4 digits

/(FMH[a-zA-Z0-9]{1,7},[.0-9A-Z-]{7},?(?:[a-zA-Z0-9]{6})?,?(?:\d{6})?)(?:/|\d{4})

Regex demo

Related