James James - 12 days ago 5
Java Question

Java Regex: can't assign variable to pattern.compile()

Here is my code, I have looked at the library which states it can accept a String. Not sure what the issue is here.

String currentText = "";
String regex = "";

public void prepRegex() {
currentText = textField.getText();
regex = regexField.getText();
}

public void checkFunc() {
prepRegex();

try {
Pattern regex = Pattern.compile(regex); // This doesn't work <---
Matcher regexMatcher = regex.matcher(currentText);
while (regexMatcher.find()) {
for (int i = 1; i <= regexMatcher.groupCount(); i++) {
// matched text: regexMatcher.group(i)
// match start: regexMatcher.start(i)
// match end: regexMatcher.end(i)
}
}
} catch (PatternSyntaxException ex) {
// Syntax error in the regular expression
}
}

Answer

You're referring to the variable in its own initializer:

Pattern regex = Pattern.compile(regex);
        ^ This                  ^ is the same symbol as this

If you want to refer to the instance variable (above, String regex = "";), qualify it with this:

Pattern regex = Pattern.compile(this.regex);
Comments