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

  1. Correct the regex syntax; read the chained PatternSyntaxException cause for the error index
  2. Validate with Pattern.compile(regexStr) in a test before constructing the selector
  3. 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

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


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)