Prashanth Ach
Prashanth Ach

Reputation: 49

How to extract a number from string using regex in java

I have tried using

title.substring(title.lastIndexOf("(") + 1, title.indexOf(")"));

I only want to extract year like 1899.

It works well for string like "hadoop (1899)" but is throwing errors for string "hadoop(yarn)(1980)"

Upvotes: 1

Views: 3581

Answers (2)

i_rezic
i_rezic

Reputation: 372

Hi check this example. This is regex for extracting numbers surrounded by brackets.

Here is usable code you can use:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

final String regex = "(?<=\\()\\d+(?=\\))";
final String string = "\"hadoop (1899)\"  \"hadoop(yarn)(1980)\"";

final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(string);

while (matcher.find()) {
    System.out.println("Full match: " + matcher.group(0));
    for (int i = 1; i <= matcher.groupCount(); i++) {
        System.out.println("Group " + i + ": " + matcher.group(i));
    }
}

Upvotes: 0

baao
baao

Reputation: 73241

Simply replace all but the digits within parenthesis with a regex

String foo = "hadoop (1899)"; // or "hadoop(yarn)(1980)"
System.out.println(foo.replaceAll(".*\\((\\d+)\\).*", "$1"));

Upvotes: 1

Related Questions