allnex
allnex

Reputation: 335

Pattern to extract value in Java

I have various strings that look like this:

Status-Active
Status-Inactive 10

I want to get only the status 'Active' and 'Inactive' without the space and number.

I tried with (?<=-)\S+ and worked on a website, but doing it the same in Java can't find anything.

private final Pattern reg = Pattern.compile("(?<=-)\\S+");
...
Matcher m = reg.matcher(status);
if(m.matches())
    status = m.group(0);

Upvotes: 1

Views: 301

Answers (2)

Terry Li
Terry Li

Reputation: 17268

I wouldn't use regex in your case, instead:

status = line.contains("Inactive")?"Inactive":"Active";

Upvotes: 1

sprinter
sprinter

Reputation: 27966

I recommend you have a pattern that is as close to the matched string as possible.

Pattern patter = Pattern.compile("Status-(Active|Inactive)");

And then use group 1 to find the status string.

Upvotes: 5

Related Questions