code4craft/webmagic · error · IllegalArgumentException
invalid regex
Error message
invalid regex
What it means
ReplaceSelector compiles its regexStr in the constructor and rethrows PatternSyntaxException as IllegalArgumentException("invalid regex", e). Unlike RegexSelector, the message does not embed the pattern, so inspect the cause for details.
Solutions
- Correct the regex syntax; read the chained PatternSyntaxException cause for the error index
- Validate with Pattern.compile(regexStr) in a test before constructing the selector
- Use Pattern.quote() or double backslashes for literals containing metacharacters/backslashes
Example fix
// before
new ReplaceSelector("C:\\users\\(.*?)", "");
// after
new ReplaceSelector(Pattern.quote("C:\\users\\") + "(.*?)", ""); Defensive patterns
Strategy: try-catch
Validate before calling
try { java.util.regex.Pattern.compile(regexStr); } catch (PatternSyntaxException e) { /* invalid */ } Try / catch
try { sel = new ReplaceSelector(regexStr, repl); } catch (IllegalArgumentException e) { throw new ConfigException("bad replace pattern", e.getCause()); } Prevention
- Double-check backslashes and escapes in replacement patterns
- Validate patterns in tests before deployment
- Log the cause PatternSyntaxException since the message omits the pattern
When it happens
Trigger: new ReplaceSelector(badRegex, replacement) where badRegex is not a valid Java regex — e.g. unbalanced parentheses, invalid escape like '\q', or trailing backslash.
Common situations: Replacing text in extracted values with a regex ported from another language; config-provided replacement patterns with typos; Windows path strings used unescaped as patterns (backslashes).
Related errors
- invalid regex
- regex must not be empty
- XPath can not apply to plain text. Please check whether you…
- $ can not apply to plain text. Please check whether you use…
- Links can not apply to plain text. Please check whether you…
AI-assisted analysis of code4craft/webmagic@67816a19d6 (2026-09-08).
Data as JSON: /api/errors/39e335bc91def2f5.
Report an issue: GitHub.
Appendix: source
Thrown at webmagic-core/src/main/java/us/codecraft/webmagic/selector/ReplaceSelector.java:28
*
* @author code4crafter@gmail.com <br>
* @since 0.1.0
*/
public class ReplaceSelector implements Selector {
private String regexStr;
private String replacement;
private Pattern regex;
public ReplaceSelector(String regexStr, String replacement) {
this.regexStr = regexStr;
this.replacement = replacement;
try {
regex = Pattern.compile(regexStr);
} catch (PatternSyntaxException e) {
throw new IllegalArgumentException("invalid regex", e);
}
}
@Override
public String select(String text) {
Matcher matcher = regex.matcher(text);
return matcher.replaceAll(replacement);
}
@Override
public List<String> selectList(String text) {
throw new UnsupportedOperationException();
}
@Override
public String toString() {
return regexStr + "_" + replacement;
}View on GitHub (pinned to 67816a19d6)