Java Regex Capture String After Specific String

后端 未结 1 748
梦谈多话
梦谈多话 2021-01-27 19:45

I need to capture the \"456456\" in

Status: Created | Ref ID: 456456 | Name: dfg  | Address: 123

with no whitespaces

I got a working

1条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-27 20:33

    Is there any way to get support for \K?

    You could conceivably use a third-party regex library that provides it. You cannot get it in the standard library's Pattern class.

    or a different regex?

    I'm uncertain whether you recognize that "capture" is a technical term in the regex space that bears directly on the question. It is indeed the usual way to go about what you describe, but the regex you present doesn't do any capturing at all. To capture the desired text with a Java regex, you want to put parentheses into the pattern, around the part whose match you want to capture:

    \bRef ID:\s+(\S+)
    

    In case of a successful match, you access the captured group via the Matcher's group() method:

    String s = "Status: Created | Ref ID: 456456 | Name: dfg  | Address: 123";
    Pattern pattern = Pattern.compile("\\bRef ID:\\s+(\\S+)");
    Matcher matcher = pattern.matcher(s);
    
    if (matcher.find()) {
        String refId = matcher.group(1);
        // ...
    }
    

    Note that you need to use matcher.find() with that regex, not matcher.matches(), because the latter tests whether the whole string matches, whereas the former tests only whether there is a substring that matches.

    0 讨论(0)
提交回复
热议问题