Example usage for java.util.regex PatternSyntaxException PatternSyntaxException

List of usage examples for java.util.regex PatternSyntaxException PatternSyntaxException

Introduction

In this page you can find the example usage for java.util.regex PatternSyntaxException PatternSyntaxException.

Prototype

public PatternSyntaxException(String desc, String regex, int index) 

Source Link

Document

Constructs a new instance of this class.

Usage

From source file:com.yahoo.flowetl.core.util.RegexUtil.java

/**
 * Gets the pattern for the given string by providing the rules to do
 * extraction./*from  w w  w.  j  a  va2  s. c o  m*/
 * 
 * This is similar to how php does regex to match you provide in the format
 * /REGEX/options where options currently are "i" for case insensitive and
 * "u" for unicode and "m" for multiline and "s" for dotall and the value
 * inside the // is the regex to use
 * 
 * @param str
 *            the string to parsed the pattern out of
 * 
 * @param cache
 *            whether to cache the compiled pattern
 * 
 * @return the pattern
 * 
 * @throws PatternSyntaxException
 * 
 *             the pattern syntax exception if it has wrong syntax
 */
public static Pattern getPattern(String str, boolean cache) throws PatternSyntaxException {
    if (str == null) {
        return null;
    }
    // see if we made it before...
    Pattern p = compiledPats.get(str);
    if (p != null) {
        return p;
    }
    Matcher mat = patExtractor.matcher(str);
    if (mat.matches() == false) {
        throw new PatternSyntaxException("Invalid syntax provided", str, -1);
    }
    String regex = mat.group(1);
    String opts = mat.group(2);
    int optsVal = 0;
    if (StringUtils.contains(opts, "i")) {
        optsVal |= Pattern.CASE_INSENSITIVE;
    }
    if (StringUtils.contains(opts, "u")) {
        optsVal |= Pattern.UNICODE_CASE;
    }
    if (StringUtils.contains(opts, "m")) {
        optsVal |= Pattern.MULTILINE;
    }
    if (StringUtils.contains(opts, "s")) {
        optsVal |= Pattern.DOTALL;
    }
    // compile and store it
    p = Pattern.compile(regex, optsVal);
    if (cache) {
        compiledPats.put(str, p);
    }
    return p;
}

From source file:ai.susi.mind.SusiSkill.java

/**
 * Generate a set of skills from a single skill definition. This may be possible if the skill contains an 'options'
 * object which creates a set of skills, one for each option. The options combine with one set of phrases
 * @param json - a multi-skill definition
 * @return a set of skills//from   ww  w .  j a v a2s. c  om
 */
public static List<SusiSkill> getSkills(JSONObject json) {
    if (!json.has("phrases"))
        throw new PatternSyntaxException("phrases missing", "", 0);
    final List<SusiSkill> skills = new ArrayList<>();
    if (json.has("options")) {
        JSONArray options = json.getJSONArray("options");
        for (int i = 0; i < options.length(); i++) {
            JSONObject option = new JSONObject();
            option.put("phrases", json.get("phrases"));
            JSONObject or = options.getJSONObject(i);
            for (String k : or.keySet())
                option.put(k, or.get(k));
            skills.add(new SusiSkill(option));
        }
    } else {
        try {
            SusiSkill skill = new SusiSkill(json);
            skills.add(skill);
        } catch (PatternSyntaxException e) {
            Logger.getLogger("SusiSkill")
                    .warning("Regular Expression error in Susi Skill: " + json.toString(2));
        }
    }
    return skills;
}

From source file:org.kalypso.commons.databinding.validation.StringRegexValidator.java

@Override
protected IStatus doValidate(final String value) {
    try {// w  ww  . j a v  a 2 s  .  c  om
        if (value == null || value.length() == 0)
            throw new PatternSyntaxException(Messages.getString("StringRegexValidator_0"), StringUtils.EMPTY, //$NON-NLS-1$
                    -1);

        Pattern.compile(value);
        return Status.OK_STATUS;
    } catch (final PatternSyntaxException ex) {
        return new Status(IStatus.ERROR, KalypsoCommonsPlugin.getID(),
                String.format(Messages.getString("StringRegexValidator_1"), ex.getLocalizedMessage()), ex); //$NON-NLS-1$
    }
}

From source file:org.loklak.susi.SusiRule.java

/**
 * Create a rule by parsing of the rule description
 * @param json the rule description// www .  j  a  v  a  2  s  .co m
 * @throws PatternSyntaxException
 */
public SusiRule(JSONObject json) throws PatternSyntaxException {

    // extract the phrases and the phrases subscore
    if (!json.has("phrases"))
        throw new PatternSyntaxException("phrases missing", "", 0);
    JSONArray p = (JSONArray) json.remove("phrases");
    this.phrases = new ArrayList<>(p.length());
    p.forEach(q -> this.phrases.add(new SusiPhrase((JSONObject) q)));

    // extract the actions and the action subscore
    if (!json.has("actions"))
        throw new PatternSyntaxException("actions missing", "", 0);
    p = (JSONArray) json.remove("actions");
    this.actions = new ArrayList<>(p.length());
    p.forEach(q -> this.actions.add(new SusiAction((JSONObject) q)));

    // extract the inferences and the process subscore; there may be no inference at all
    if (json.has("process")) {
        p = (JSONArray) json.remove("process");
        this.inferences = new ArrayList<>(p.length());
        p.forEach(q -> this.inferences.add(new SusiInference((JSONObject) q)));
    } else {
        this.inferences = new ArrayList<>(0);
    }

    // extract (or compute) the keys; there may be none key given, then they will be computed
    this.keys = new HashSet<>();
    JSONArray k;
    if (json.has("keys")) {
        k = json.getJSONArray("keys");
        if (k.length() == 0 || (k.length() == 1 && k.getString(0).length() == 0))
            k = computeKeysFromPhrases(this.phrases);
    } else {
        k = computeKeysFromPhrases(this.phrases);
    }

    k.forEach(o -> this.keys.add((String) o));

    this.user_subscore = json.has("score") ? json.getInt("score") : DEFAULT_SCORE;
    this.score = -1; // calculate this later if required

    // extract the comment
    this.comment = json.has("comment") ? json.getString("comment") : "";

    // calculate the id
    String ids0 = this.actions.toString();
    String ids1 = this.phrases.toString();
    this.id = ids0.hashCode() + ids1.hashCode();
}

From source file:org.loklak.susi.SusiPhrase.java

/**
 * Create a phrase using a json data structure containing the phrase description.
 * The json must contain at least two properties:
 *   type: the name of the phrase type which means: what language is used for the pattern
 *   expression: the pattern string using either regular expressions or simple patterns
 * @param json the phrase description//  w ww . j  av a  2 s  .  c  o  m
 * @throws PatternSyntaxException
 */
public SusiPhrase(JSONObject json) throws PatternSyntaxException {
    if (!json.has("expression"))
        throw new PatternSyntaxException("expression missing", "", 0);
    String expression = json.getString("expression").toLowerCase();
    Type t = Type.pattern;
    if (json.has("type"))
        try {
            t = Type.valueOf(json.getString("type"));
        } catch (IllegalArgumentException e) {
            Log.error("type value is wrong: " + json.getString("type"));
            t = expression.indexOf(".*") >= 0 ? Type.regex
                    : expression.indexOf('*') >= 0 ? Type.pattern : Type.minor;
        }

    expression = normalizeExpression(expression);
    if ((t == Type.minor || t == Type.prior) && expression.indexOf(".*") >= 0)
        t = Type.regex;
    if ((t == Type.minor || t == Type.prior) && expression.indexOf('*') >= 0)
        t = Type.pattern;
    if (t == Type.pattern)
        expression = parsePattern(expression);
    this.pattern = Pattern.compile(expression);
    this.type = expression.equals("(.*)") ? Type.minor : t;
    this.hasCaptureGroups = expression.replaceAll("\\(\\?", "").indexOf('(') >= 0;

    // measure the meat size
    this.meatsize = Math.min(99, extractMeat(expression).length());
}

From source file:ai.susi.mind.SusiPhrase.java

/**
 * Create a phrase using a json data structure containing the phrase description.
 * The json must contain at least two properties:
 *   type: the name of the phrase type which means: what language is used for the pattern
 *   expression: the pattern string using either regular expressions or simple patterns
 * @param json the phrase description/*from  w  w w .j a v  a 2  s  .  com*/
 * @throws PatternSyntaxException
 */
public SusiPhrase(JSONObject json) throws PatternSyntaxException {
    if (!json.has("expression"))
        throw new PatternSyntaxException("expression missing", "", 0);
    String expression = json.getString("expression").toLowerCase();

    Type t = Type.pattern;
    if (json.has("type"))
        try {
            t = Type.valueOf(json.getString("type"));
        } catch (IllegalArgumentException e) {
            Logger.getLogger("SusiPhrase").warning("type value is wrong: " + json.getString("type"));
            t = expression.indexOf(".*") >= 0 ? Type.regex
                    : expression.indexOf('*') >= 0 ? Type.pattern : Type.minor;
        }

    expression = normalizeExpression(expression);
    if ((t == Type.minor || t == Type.prior) && expression.indexOf(".*") >= 0)
        t = Type.regex;
    if ((t == Type.minor || t == Type.prior) && expression.indexOf('*') >= 0)
        t = Type.pattern;
    if (t == Type.pattern)
        expression = parsePattern(expression);
    this.pattern = Pattern.compile(expression);
    this.type = expression.equals("(.*)") ? Type.minor : t;
    this.hasCaptureGroups = expression.replaceAll("\\(\\?", "").indexOf('(') >= 0;

    // measure the meat size
    this.meatsize = Math.min(99, extractMeat(expression).length());
}

From source file:org.apache.hadoop.chukwa.util.Filter.java

public Filter(String listOfPatterns) throws PatternSyntaxException {
    compiledPatterns = new ArrayList<SearchRule>();
    //FIXME: could escape these
    String[] patterns = listOfPatterns.split(SEPARATOR);
    for (String p : patterns) {
        int equalsPos = p.indexOf('=');

        if (equalsPos < 0 || equalsPos > (p.length() - 2)) {
            throw new PatternSyntaxException("pattern must be of form targ=pattern", p, -1);
        }//w  w w  .ja  va2  s .c  o m

        String targ = p.substring(0, equalsPos);
        if (!targ.startsWith("tags.") && !ArrayUtils.contains(SEARCH_TARGS, targ)) {
            throw new PatternSyntaxException("pattern doesn't start with recognized search target", p, -1);
        }

        Pattern pat = Pattern.compile(p.substring(equalsPos + 1), Pattern.DOTALL);
        compiledPatterns.add(new SearchRule(pat, targ));
    }
}

From source file:nl.toolforge.karma.core.module.BaseModule.java

public BaseModule(String name, Location location) {

    if (!name.matches(ModuleDigester.NAME_PATTERN_STRING)) {
        throw new PatternSyntaxException(
                "Pattern mismatch for 'name'. Should match " + ModuleDigester.NAME_PATTERN_STRING, name, -1);
    }/*from   w w w . j av a  2 s  .  c o m*/
    if (location == null) {
        throw new IllegalArgumentException("Location cannot be null.");
    }

    this.name = name;
    this.location = location;
}

From source file:ai.susi.mind.SusiSkill.java

/**
 * Create a skill by parsing of the skill description
 * @param json the skill description//from   w w w.j av  a 2  s .  c  om
 * @throws PatternSyntaxException
 */
private SusiSkill(JSONObject json) throws PatternSyntaxException {

    // extract the phrases and the phrases subscore
    if (!json.has("phrases"))
        throw new PatternSyntaxException("phrases missing", "", 0);
    JSONArray p = (JSONArray) json.remove("phrases");
    this.phrases = new ArrayList<>(p.length());
    p.forEach(q -> this.phrases.add(new SusiPhrase((JSONObject) q)));

    // extract the actions and the action subscore
    if (!json.has("actions"))
        throw new PatternSyntaxException("actions missing", "", 0);
    p = (JSONArray) json.remove("actions");
    this.actions = new ArrayList<>(p.length());
    p.forEach(q -> this.actions.add(new SusiAction((JSONObject) q)));

    // extract the inferences and the process subscore; there may be no inference at all
    if (json.has("process")) {
        p = (JSONArray) json.remove("process");
        this.inferences = new ArrayList<>(p.length());
        p.forEach(q -> this.inferences.add(new SusiInference((JSONObject) q)));
    } else {
        this.inferences = new ArrayList<>(0);
    }

    // extract (or compute) the keys; there may be none key given, then they will be computed
    this.keys = new HashSet<>();
    JSONArray k;
    if (json.has("keys")) {
        k = json.getJSONArray("keys");
        if (k.length() == 0 || (k.length() == 1 && k.getString(0).length() == 0))
            k = computeKeysFromPhrases(this.phrases);
    } else {
        k = computeKeysFromPhrases(this.phrases);
    }

    k.forEach(o -> this.keys.add((String) o));

    this.user_subscore = json.has("score") ? json.getInt("score") : DEFAULT_SCORE;
    this.score = null; // calculate this later if required

    // extract the comment
    this.comment = json.has("comment") ? json.getString("comment") : "";

    // calculate the id
    String ids0 = this.actions.toString();
    String ids1 = this.phrases.toString();
    this.id = ids0.hashCode() + ids1.hashCode();
}

From source file:brainflow.app.presentation.controls.FileObjectGroupSelector.java

private static String globToRegexPattern(final String glob) throws PatternSyntaxException {
    /* Stack to keep track of the parser mode: */
    /* "--" : Base mode (first on the stack)   */
    /* "[]" : Square brackets mode "[...]"     */
    /* "{}" : Curly braces mode "{...}"        */
    final Deque<String> parserMode = new ArrayDeque<String>();
    parserMode.push("--"); // base mode

    final int globLength = glob.length();
    int index = 0; // index in glob

    /* equivalent REGEX expression to be compiled */
    final StringBuilder t = new StringBuilder();

    while (index < globLength) {
        char c = glob.charAt(index++);

        if (c == '\\') {
            /***********************
             * (1) ESCAPE SEQUENCE *//from  w w w. jav a 2s .  c o m
             ***********************/

            if (index == globLength) {
                /* no characters left, so treat '\' as literal char */
                t.append(Pattern.quote("\\"));
            } else {
                /* read next character */
                c = glob.charAt(index);
                final String s = c + "";

                if (("--".equals(parserMode.peek()) && "\\[]{}?*".contains(s))
                        || ("[]".equals(parserMode.peek()) && "\\[]{}?*!-".contains(s))
                        || ("{}".equals(parserMode.peek()) && "\\[]{}?*,".contains(s))) {
                    /* escape the construct char */
                    index++;
                    t.append(Pattern.quote(s));
                } else {
                    /* treat '\' as literal char */
                    t.append(Pattern.quote("\\"));
                }
            }
        } else if (c == '*') {
            /************************
             * (2) GLOB PATTERN '*' *
             ************************/

            /* create non-capturing group to match zero or more characters */
            t.append(".*");
        } else if (c == '?') {
            /************************
             * (3) GLOB PATTERN '?' *
             ************************/

            /* create non-capturing group to match exactly one character */
            t.append('.');
        } else if (c == '[') {
            /****************************
             * (4) GLOB PATTERN "[...]" *
             ****************************/

            /* opening square bracket '[' */
            /* create non-capturing group to match exactly one character */
            /* inside the sequence */
            t.append('[');
            parserMode.push("[]");

            /* check for negation character '!' immediately after */
            /* the opening bracket '[' */
            if ((index < globLength) && (glob.charAt(index) == '!')) {
                index++;
                t.append('^');
            }
        } else if ((c == ']') && "[]".equals(parserMode.peek())) {
            /* closing square bracket ']' */
            t.append(']');
            parserMode.pop();
        } else if ((c == '-') && "[]".equals(parserMode.peek())) {
            /* character range '-' in "[...]" */
            t.append('-');
        } else if (c == '{') {
            /****************************
             * (5) GLOB PATTERN "{...}" *
             ****************************/

            /* opening curly brace '{' */
            /* create non-capturing group to match one of the */
            /* strings inside the sequence */
            t.append("(?:(?:");
            parserMode.push("{}");
        } else if ((c == '}') && "{}".equals(parserMode.peek())) {
            /* closing curly brace '}' */
            t.append("))");
            parserMode.pop();
        } else if ((c == ',') && "{}".equals(parserMode.peek())) {
            /* comma between strings in "{...}" */
            t.append(")|(?:");
        } else {
            /*************************
             * (6) LITERAL CHARACTER *
             *************************/

            /* convert literal character to a regex string */
            t.append(Pattern.quote(c + ""));
        }
    }
    /* done parsing all chars of the source pattern string */

    /* check for mismatched [...] or {...} */
    if ("[]".equals(parserMode.peek()))
        throw new PatternSyntaxException("Cannot find matching closing square bracket ] in GLOB expression",
                glob, -1);

    if ("{}".equals(parserMode.peek()))
        throw new PatternSyntaxException("Cannot find matching closing curly brace } in GLOB expression", glob,
                -1);

    return t.toString();
}