简体   繁体   中英

Java Regex Capture String After Specific String

I need to capture the "456456" in

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

with no whitespaces

I got a working regex and later find out that java does not support \\K.

\bRef ID:\s+\K\S+

Is there any way to get support for \\K?
or a different regex?
Any help would be much appreciated.

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.

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