I need to capture the \"456456\" in
Status: Created | Ref ID: 456456 | Name: dfg | Address: 123
with no whitespaces
I got a working
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.