1

I have a pattern like below

Sentence = "@502348@502002662[000861@10";
Pattern = "^@(\\d{6})@*(\\d{9})\\[(\\d{6})@(\\d{2})";

Matcher regexMatcher = regexPattern.matcher(Sentence);
    if (regexMatcher.find()) 
      str1= regexMatcher.group(1);
      str2 = regexMatcher.group(2);
      str3 = regexMatcher.group(3);
      str4 = regexMatcher.group(4);
    }

The above one works fine if the sentence is appropriately matches. But my requirement is , the partial result should be returned in case the pattern is not matches appropriately.

For example if Sentence = "@114142@000017000[" then i want to get the str1 and str2.

Thanks

0

2 Answers 2

1

You can use make last part optional:

^@(\\d{6})@*(\\d{9})(?:\\[(\\d{6})@(\\d{2}))?

RegEx Demo

Sign up to request clarification or add additional context in comments.

Comments

1

I am not sure if this is what you are looking for but you can try something like

^@(\\d{6})(?:@*(\\d{9})(?:\\[(\\d{6})(?:@(\\d{2}))?)?)?

This makes

@xxxxxx@xxxxxxxxx[xxxxxx@xx
       ^^^^^^^^^^^^^^^^^^^^ - optional
                 ^^^^^^^^^^ - optional
                         ^^ - optional

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.