'How to capture empty groups in the input string in java

I have a scenario where I would like to capture a fixed number of groups.

For e.g Input string : A B C D E

Output must be 5 groups: A,B,C,D,E input string: A E Outputs groups A,null,null,null,E Input String: A B E Output group: A,B,null,null,E

I always have A and E in the input string and the between parts may or may not be present. If they are then they need to be captured if not capture empty of null.

What could the possible java regex for this?



Solution 1:[1]

You may try that:

(A)\h*(B)?\h*(C)?\h*(D)?\h*(E)

Explanation:

  1. I have kept 5 letters in 5 groups as you have mentioned.
  2. But also kept optional mark ? for B,C and D.
  3. So group 1 is always A and Group 5 is always E.
  4. \h means horizontal white spaces.* - It may or may not appear in your string.

Regex demo

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1