I modified the following code from Oracle’s Java Tutorials:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class RegexTestHarness {
public static void main(String[] args){
while (true) {
Pattern pattern = Pattern.compile("foo");
Matcher matcher = pattern.matcher("foo foo foo");
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.format("No match found.%n");
}
}
}
}
I am trying to learn how to use regular expressions in Java. (I feel pretty confident about regex’s, just not with Java’s classes for using them.) I am using Eclipse, which I am also not incredibly familar with. I could not figure out how to get the console to not be initialized to null (as the tutorial warned), so I removed it and am just using static values and recompiling every time I want to try something new.
When I run this code, I get an infinite loop:
I found the text "foo" starting at index 0 and ending at index 3.
I found the text "foo" starting at index 4 and ending at index 7.
I found the text "foo" starting at index 8 and ending at index 11.
I found the text "foo" starting at index 0 and ending at index 3.
etc., etc., etc. until I hit terminate
What am I doing wrong?
Thanks.
Nevermind… >.< For some reason I didn’t see the infinite loop on the outside. I assumed the whole time that it was the other loop that was the problem.
You currently have a
while(true)arround that section of your code.while(true)is an infinite loop, and you never seem to break out of it.