Why does my Regular Expression ignore the last character in each match

Viewed 178

Below regex works properly except that it ignores the last character in each match.

\d{4}\b.*?(?=[^:]\d{4}(?! ml| kg)( [A-Za-z]{2}| \d{1}-| 1H-| [A-Za-z0-9],[A-Za-z0-9]| \D{1}-)|$)

My question is: How can this be updated to also include the last character in each match

Below an example of the data:
https://regex101.com/r/XRlr4Q/1

2 Answers

The [^:] pattern in the lookahead requires a char other than : before the first four digits of a match.

You need to use a lookbehind (?<!:) there:

\d{4}\b.*?(?=(?<!:)\d{4}(?! ml| kg)(?: [A-Za-z]{2}| \d-| 1H-| [A-Za-z0-9],[A-Za-z0-9]| \D-)|$)

See the regex demo.

I rewrote a bit your Regex to match

  • 4 digits
  • Followed by your special char and unlimited [A-a]
  • Then a positive lookahead to match everything until it sees the start sequence again or the end of file

I removed some things which you can add again if needed, but it works with your dataset.

\d{4}( [A-a]+).+?(?=\d{4}( [A-a]+) | $)

Here an example based on your DataSet : https://regex101.com/r/HWYJEf/1

Related