1
\$\begingroup\$

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.");
    }
}
\$\endgroup\$
1
  • \$\begingroup\$ 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? \$\endgroup\$
    – holroy
    Mar 3, 2016 at 13:51

1 Answer 1

1
\$\begingroup\$

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);
    ...
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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