JavaUser
JavaUser

Reputation: 26344

get the partial match string using java regex pattern

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

Upvotes: 1

Views: 139

Answers (2)

Pshemo
Pshemo

Reputation: 124225

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

Upvotes: 1

anubhava
anubhava

Reputation: 785146

You can use make last part optional:

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

RegEx Demo

Upvotes: 1

Related Questions