code4craft/webmagic · error · IllegalArgumentException
regex must not be empty
Error message
regex must not be empty
What it means
RegexSelector validates its pattern in compileRegex and throws IllegalArgumentException when the regex string is null, empty, or blank. A regex selector without a pattern cannot match anything, so construction is refused immediately.
Solutions
- Supply a non-blank regex string to the RegexSelector constructor
- Validate the pattern with StringUtils.isNotBlank(regex) before constructing the selector
- Fix the config/source that yields the empty value
Example fix
// before
Selectable sel = new RegexSelector("");
// after
Selectable sel = new RegexSelector("<title>(.*?)</title>"); Defensive patterns
Strategy: validation
Validate before calling
if (regexStr == null || regexStr.trim().isEmpty()) { throw new IllegalArgumentException("regex required"); } Try / catch
try { sel = new RegexSelector(cfgRegex); } catch (IllegalArgumentException e) { log.error("blank/invalid regex config", e); sel = defaultSelector; } Prevention
- Validate regex config values at startup with StringUtils.isNotBlank
- Fail fast on empty settings files
- Provide sane default patterns
When it happens
Trigger: new RegexSelector("") or new RegexSelector(null); passing an empty regexStr read from blank configuration; RegexSelector created with a blank string variable.
Common situations: Regex pulled from a properties file or user input that is empty; default config value left unfilled; string concatenation producing an empty pattern.
Related errors
- invalid regex
- invalid regex
- Only one of 'ExtractBy ComboExtract ExtractByUrl' can be…
- XPath can not apply to plain text. Please check whether you…
- $ can not apply to plain text. Please check whether you use…
AI-assisted analysis of code4craft/webmagic@67816a19d6 (2026-09-08).
Data as JSON: /api/errors/4d1eebb42a6a8a51.
Report an issue: GitHub.
Appendix: source
Thrown at webmagic-core/src/main/java/us/codecraft/webmagic/selector/RegexSelector.java:32
* @author code4crafter@gmail.com <br>
* @since 0.1.0
*/
public class RegexSelector implements Selector {
private String regexStr;
private Pattern regex;
private int group = 1;
public RegexSelector(String regexStr, int group) {
this.compileRegex(regexStr);
this.group = group;
}
private void compileRegex(String regexStr) {
if (StringUtils.isBlank(regexStr)) {
throw new IllegalArgumentException("regex must not be empty");
}
try {
this.regex = Pattern.compile(regexStr, Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
this.regexStr = regexStr;
} catch (PatternSyntaxException e) {
throw new IllegalArgumentException("invalid regex "+regexStr, e);
}
}
/**
* Create a RegexSelector. When there is no capture group, the value is set to 0 else set to 1.
* @param regexStr the regular expression.
*/
public RegexSelector(String regexStr) {
this.compileRegex(regexStr);
if (regex.matcher("").groupCount() == 0) {
this.group = 0;
} else {View on GitHub (pinned to 67816a19d6)