Davut Gürbüz
Davut Gürbüz

Reputation: 5756

Optional components in java regex

I've been writing regex for long time and covering below scenarios by writing two regexes, since I do not know if there's a way to handle it by a single regex. So, I would like to hear if there's a way to write a single regex to capture the both at one shot.

Suppose that we have a standard starting with A and ending with Z, the field delimiter is a pipe | and each field consist of components delimited by a hat ^.

The regex should give below output

My attempt : A\|.\d*\|(.*)\^(.*)\^(.*)\^(.*)\^(.*?)\|.+?\|Z works for the first input but not the second.

What regex matches both inputs and gets the groups in correct order ?

[UPDATE] Group order is important. So group 1 should be 1, group 2 should be returning an empty and 2 in respectively for input 1 and input 2. Because based on the order they have different meanings in the standard.

Upvotes: 0

Views: 53

Answers (1)

Davut Gürbüz
Davut Gürbüz

Reputation: 5756

I'm sharing this onbehalf of @MikeM, who answered originaly to this question.

A\|\d*\|(?:(\d*)\^?)?(?:(\d*)\^?)?(?:(\d*)\^?)?(?:(\d*)\^?)?(?:(\d*))\|.+?\|Z

This regex matches all 3 inputs in the right group order. Thanks.

Upvotes: 1

Related Questions