Reputation: 26344
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
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
Reputation: 785146
You can use make last part optional:
^@(\\d{6})@*(\\d{9})(?:\\[(\\d{6})@(\\d{2}))?
Upvotes: 1