1

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)"

2
  • Welcome to Stack Overflow! Please review our SO Question Checklist to help you to ask a good question, and thus get a good answer. Commented Apr 12, 2017 at 21:35
  • Why not use lastIndexOf for both parenthesis (assuming you are interested in data from last parenthesis)? Commented Apr 12, 2017 at 21:37

2 Answers 2

1

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"));
Sign up to request clarification or add additional context in comments.

Comments

0

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));
    }
}

1 Comment

If u want to know more about regex used, check right sidebar, it explains what each symbol/char means.

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.