Code Review Stack Exchange is a question and answer site for peer programmer code reviews. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm new to Java and is trying to find a substring within a string using regular Expressions. I was just wondering if there are any alternative ways to achieve the same goal, or in a more elegant or efficient manner.

while (true) {

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("\nEnter your regex:");

    Pattern pattern
            = Pattern.compile(br.readLine());

    System.out.println("\nEnter input string to search:");
    Matcher matcher
            = pattern.matcher(br.readLine());

    boolean found = false;
    while (matcher.find()) {
        System.out.format("I found the text"
                + " \"%s\" starting at "
                + "index %d and ending at index %d.%n",
                matcher.group(),
                matcher.start(),
                matcher.end());
        found = true;
    }
    if (!found) {
        System.out.println("No match found.");
    }
}
share|improve this question
    
It is not clear to me what you want to do here as your code allows for all kinds of regex being entered. What is the main goal and requirements? Cos you also give some examples of input and expected output? – holroy Mar 3 at 13:51
up vote 1 down vote accepted

You code is pretty much good but

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

may be easily replaced with

Console br = System.console();

Also your while cycle is endless. I would allow to enter some keyword for breaking the loop. E.g. exit

...
System.out.println("\nEnter your regex:");
String input = br.readLine();

if ("exit".equals(input)) 
    break;
else {
    Pattern pattern = Pattern.compile(input);
    ...
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.