1

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.

7
  • 1
    What's wrong with captured group: \bRef ID:\s+(\S+) Commented Jun 20, 2016 at 16:29
  • From what I know, you can even use (?<=Ref ID:\s+)\S+ (as Android patterns use an ICU regex flavor). However, capturing is what you need. Commented Jun 20, 2016 at 16:31
  • @anubhava that is capturing Ref ID and the number. I am trying to get just the number after Ref ID. Commented Jun 20, 2016 at 16:38
  • @WiktorStribiżew i get an invalid regex on (?<=Ref ID:\s+)\S+ Commented Jun 20, 2016 at 16:39
  • Thank you, so that means the bug was fixed. And what about (?<=Ref ID:\s{1,1000})\S+? Commented Jun 20, 2016 at 16:40

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

More (flavor-agnostic) information on regular expression groups/capturing.
Thank you for clarifying some things for me. The regex you provided solved my problem. And your explanation gave me a much better understanding .A+

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.