magicsword
magicsword

Reputation: 1289

regex in parentheses

I have the following string:

(20% up)

I want to extract 20

I've tried \(([^%]+)\)

But can't get the value alone.

Upvotes: 1

Views: 41

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626871

You can use

(?<=\()\d+(?=%[^()]*\))

See this regex demo.

Details

  • (?<=\() - a ( must appear immediately on the left
  • \d+ - one or more digits
  • (?=%[^()]*\)) - a % and any zero or more chars other than ( and ) followed with ) must appear immediately on the right.

Upvotes: 1

WJS
WJS

Reputation: 40034

Here is how you might do it in java.

  • (\\d+) captures the 20
  • If you specifically want to focus on that followed by a space and up you can put those in after the % sign. e.g ( (\\d+)% up )
String s = "(20% up)";
Matcher m = Pattern.compile("(\\d+)%").matcher(s);
if (m.find()) {
    System.out.println(m.group(1));
}

Prints

20

Upvotes: 0

Related Questions