简体   繁体   中英

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

You can use make last part optional:

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

RegEx Demo

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM