Java Code Examples for java.util.regex.PatternSyntaxException

The following are top voted examples for showing how to use java.util.regex.PatternSyntaxException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: L2J-Global   File: PetNameTable.java   View source code 6 votes vote down vote up
public boolean isValidPetName(String name)
{
	boolean result = true;
	
	if (!isAlphaNumeric(name))
	{
		return result;
	}
	
	Pattern pattern;
	try
	{
		pattern = Pattern.compile(Config.PET_NAME_TEMPLATE);
	}
	catch (PatternSyntaxException e) // case of illegal pattern
	{
		LOGGER.warning(getClass().getSimpleName() + ": Pet name pattern of config is wrong!");
		pattern = Pattern.compile(".*");
	}
	final Matcher regexp = pattern.matcher(name);
	if (!regexp.matches())
	{
		result = false;
	}
	return result;
}
 
Example 2
Project: cyberduck   File: PreferencesController.java   View source code 6 votes vote down vote up
public void uploadSkipRegexFieldDidChange(NSNotification sender) {
    String value = this.uploadSkipRegexField.string().trim();
    if(StringUtils.EMPTY.equals(value)) {
        preferences.setProperty("queue.upload.skip.enable", false);
        preferences.setProperty("queue.upload.skip.regex", value);
        this.uploadSkipButton.setState(NSCell.NSOffState);
    }
    try {
        Pattern compiled = Pattern.compile(value);
        preferences.setProperty("queue.upload.skip.regex",
                compiled.pattern());
        this.mark(this.uploadSkipRegexField.textStorage(), null);
    }
    catch(PatternSyntaxException e) {
        this.mark(this.uploadSkipRegexField.textStorage(), e);
    }
}
 
Example 3
Project: apache-tomcat-7.0.73-with-comment   File: ExpressionParseTree.java   View source code 6 votes vote down vote up
protected int compareBranches() {
    String val1 = ((StringNode)left).getValue();
    String val2 = ((StringNode)right).getValue();
    
    int val2Len = val2.length();
    if (val2Len > 1 && val2.charAt(0) == '/' &&
            val2.charAt(val2Len - 1) == '/') {
        // Treat as a regular expression
        String expr = val2.substring(1, val2Len - 1);
        try {
            Pattern pattern = Pattern.compile(expr);
            // Regular expressions will only ever be used with EqualNode
            // so return zero for equal and non-zero for not equal
            if (pattern.matcher(val1).find()) {
                return 0;
            } else {
                return -1;
            }
        } catch (PatternSyntaxException pse) {
            ssiMediator.log("Invalid expression: " + expr, pse);
            return 0;
        }
    }
    return val1.compareTo(val2);
}
 
Example 4
Project: L2jBrasil   File: EnterWorld.java   View source code 6 votes vote down vote up
private static boolean isValidName(String text)
{
    boolean result = true;
    String test = text;
    Pattern pattern;
    try
    {
        pattern = Pattern.compile(Config.CNAME_TEMPLATE);
    }
    catch(PatternSyntaxException e)
    {
        _log.warning("ERROR : Character name pattern of config is wrong!");
        pattern = Pattern.compile(".*");
    }
    Matcher regexp = pattern.matcher(test);
    if(!regexp.matches())
        result = false;
    return result;
}
 
Example 5
Project: L2jBrasil   File: CharacterCreate.java   View source code 6 votes vote down vote up
private boolean isValidName(String text)
{
        boolean result = true;
        String test = text;
        Pattern pattern;
        try
        {
            pattern = Pattern.compile(Config.CNAME_TEMPLATE);
        }
        catch (PatternSyntaxException e) // case of illegal pattern
        {
        	_log.warning("ERROR : Character name pattern of config is wrong!");
            pattern = Pattern.compile(".*");
        }
        Matcher regexp = pattern.matcher(test);
        if (!regexp.matches())
        {
                result = false;
        }
        return result;
}
 
Example 6
Project: incubator-netbeans   File: TextRegexpUtil.java   View source code 6 votes vote down vote up
/**
 * Tries to compile the regular expression pattern, thus checking its
 * validity. In case of success, the compiled pattern is stored to {@link #textPattern},
 * otherwise the field is set to {@code null}.
 *
 * <p>Actually, this method defines a pattern used in searching, i.e. it
 * defines behaviour of the searching. It should be the same as behavior of
 * the Find action (Ctrl+F) in the Editor to avoid any confusions (see Bug
 * #175101). Hence, this implementation should specify default flags in the
 * call of the method {@link Pattern#compile(java.lang.String, int)
 * java.util.regex.Pattern.compile(String regex, int flags)} that are the
 * same as in the implementation of the Find action (i.e in the method {@code getFinder}
 * of the class {@code org.netbeans.modules.editor.lib2.search.DocumentFinder}).
 * </p>
 *
 * @return {@code true} if the regexp pattern expression was valid; {@code false}
 * otherwise
 */
private static Pattern compileRegexpPattern(SearchPattern sp)
        throws PatternSyntaxException {

    assert sp != null;
    assert sp.getSearchExpression() != null;
    assert sp.isRegExp();

    boolean multiline = canBeMultilinePattern(sp.getSearchExpression());

    if (LOG.isLoggable(Level.FINEST)) {
        LOG.log(Level.FINEST, " - textPatternExpr = \"{0}{1}",
                new Object[]{sp.getSearchExpression(), '"'});   //NOI18N
    }
    int flags = 0;
    if (!sp.isMatchCase()) {
        flags |= Pattern.CASE_INSENSITIVE;
        flags |= Pattern.UNICODE_CASE;
    }
    flags |= Pattern.MULTILINE; // #175101
    return Pattern.compile(sp.getSearchExpression(), flags);


}
 
Example 7
Project: sponge   File: TriggersTestTemplate.java   View source code 6 votes vote down vote up
public static void testTriggersEventPatternIncorrect(KnowledgeBaseType type) {
    Engine engine = null;

    try {
        engine = ScriptTestUtils.startWithKnowledgeBase(type, "triggers_event_pattern_incorrect");
        fail("Expected pattern syntax exception");
    } catch (SpongeException e) {
        if (ExceptionUtils.indexOfThrowable(e, PatternSyntaxException.class) < 0) {
            throw e;
        }
    } finally {
        if (engine != null) {
            engine.shutdown();
        }
    }
}
 
Example 8
Project: incubator-netbeans   File: FileNameController.java   View source code 6 votes vote down vote up
/**
 * Sets proper color of file pattern.
 */
private void updateFileNamePatternColor() {

    boolean wasInvalid = patternValid;
    String pattern = getFileNamePattern();

    if (pattern == null || pattern.isEmpty()) {
        patternValid = true;
    } else {
        try {
            Pattern p = RegexpUtil.makeFileNamePattern(
                    SearchScopeOptions.create(getFileNamePattern(), regexp));
            if (p == null) {
                patternValid = false;
            } else {
                patternValid = true;
            }
        } catch (PatternSyntaxException e) {
            patternValid = false;
        }
    }
    if (patternValid != wasInvalid && !isAllFilesInfoDisplayed()) {
        fileNamePatternEditor.setForeground(
                patternValid ? defaultColor : UiUtils.getErrorTextColor());
    }
}
 
Example 9
Project: incubator-netbeans   File: SvnUtils.java   View source code 6 votes vote down vote up
public static List<String> getMatchinIgnoreParterns(List<String> patterns, String value, boolean onlyFirstMatch)  {
    List<String> ret = new ArrayList<String>();
    if(patterns == null) return ret;
    for (Iterator<String> i = patterns.iterator(); i.hasNext();) {
        try {
            // may contain shell patterns (almost identical to RegExp)
            String patternString  = i.next();
            String shellPatternString = regExpToFilePatterns(patternString);
            Pattern pattern =  Pattern.compile(shellPatternString);
            if (pattern.matcher(value).matches()) {
                ret.add(patternString);
                if(onlyFirstMatch) {
                    return ret;
                }
            }
        } catch (PatternSyntaxException e) {
            // it's difference between shell and regexp
            // or user error (set invalid property), rethrow?
            Subversion.LOG.log(Level.INFO, null, e);
        }
    }
    return ret;
}
 
Example 10
Project: OpenJSharp   File: RegExpScanner.java   View source code 6 votes vote down vote up
/**
 * Scan a JavaScript regexp string returning a Java safe regex string.
 *
 * @param string
 *            JavaScript regexp string.
 * @return Java safe regex string.
 */
public static RegExpScanner scan(final String string) {
    final RegExpScanner scanner = new RegExpScanner(string);

    try {
        scanner.disjunction();
    } catch (final Exception e) {
        throw new PatternSyntaxException(e.getMessage(), string, scanner.position);
    }

    scanner.processForwardReferences();

    // Throw syntax error unless we parsed the entire JavaScript regexp without syntax errors
    if (scanner.position != string.length()) {
        final String p = scanner.getStringBuilder().toString();
        throw new PatternSyntaxException(string, p, p.length() + 1);
    }

    return scanner;
}
 
Example 11
Project: incubator-netbeans   File: ConstantNameOptions.java   View source code 6 votes vote down vote up
private void documentChanged() {
    if (suppressEvents) {
        return;
    }
    String pat = namePattern.getText().trim();
    if (!"".equals(pat)) {
        // check the pattern is OK
        try {
            Pattern p = Pattern.compile(pat);
        } catch (PatternSyntaxException ex) {
            namePattern.setBackground(errorBkColor);
            return;
        }
        namePattern.setBackground(defaultBkColor);
    }
    prefs.put(ConstantNameHint.PREF_CONSTANT_NAME_PATTERN, pat);
}
 
Example 12
Project: incubator-netbeans   File: Patch.java   View source code 6 votes vote down vote up
private static Difference[] parseNormalDiff(Reader in) throws IOException {
    Pattern normRegexp;
    try {
        normRegexp = Pattern.compile(CmdlineDiffProvider.DIFF_REGEXP);
    } catch (PatternSyntaxException rsex) {
        normRegexp = null;
    }
    StringBuffer firstText = new StringBuffer();
    StringBuffer secondText = new StringBuffer();
    BufferedReader br = new BufferedReader(in);
    List<Difference> diffs = new ArrayList<Difference>();
    String line;
    while ((line = br.readLine()) != null) {
        CmdlineDiffProvider.outputLine(line, normRegexp, diffs, firstText, secondText);
    }
    CmdlineDiffProvider.setTextOnLastDifference(diffs, firstText, secondText);
    return diffs.toArray(new Difference[diffs.size()]);
}
 
Example 13
Project: incubator-netbeans   File: JavadocSearchType.java   View source code 6 votes vote down vote up
private synchronized void prepareOverviewFilter() {
    if (overviewLabelFilters != null) {
        return;
    }
    String filter = NbBundle.getMessage(JavadocSearchType.class, "FILTER_OverviewIndiceLabel"); // NOI18N
    StringTokenizer tok = new StringTokenizer(filter, "\n"); // NOI18N
    List<Pattern> ll = new LinkedList<Pattern>();
    while (tok.hasMoreTokens()) {
        try {
            String expr = tok.nextToken();
            Pattern re = Pattern.compile(expr);
            ll.add(re);
        } catch (PatternSyntaxException e) {
            ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, e);
        }
    }
    overviewLabelFilters = ll.toArray(new Pattern[ll.size()]);
}
 
Example 14
Project: rapidminer   File: AggregationOperator.java   View source code 6 votes vote down vote up
private Attribute[] getMatchingAttributes(Attributes attributes, String regex) throws OperatorException {
	Pattern pattern = null;
	try {
		pattern = Pattern.compile(regex);
	} catch (PatternSyntaxException e) {
		throw new UserError(this, 206, regex, e.getMessage());
	}
	List<Attribute> attributeList = new LinkedList<>();
	Iterator<Attribute> iterator = attributes.allAttributes();
	while (iterator.hasNext()) {
		Attribute attribute = iterator.next();
		if (pattern.matcher(attribute.getName()).matches()) {
			attributeList.add(attribute);
		}
	}

	// building array of attributes for faster access.
	Attribute[] attributesArray = new Attribute[attributeList.size()];
	attributesArray = attributeList.toArray(attributesArray);
	return attributesArray;
}
 
Example 15
Project: MaxSim   File: Properties.java   View source code 6 votes vote down vote up
public RegexpPropertyMatcher(String name, String value, int flags) {

            if (name == null) {
                throw new IllegalArgumentException("Property name must not be null!");
            }

            if (value == null) {
                throw new IllegalArgumentException("Property value pattern must not be null!");
            }

            this.name = name;

            try {
                valuePattern = Pattern.compile(value, flags);
            } catch (PatternSyntaxException e) {
                throw new IllegalArgumentException("Bad pattern: " + value);
            }
        }
 
Example 16
Project: rapidminer   File: MidasRegexpAttributeFilter.java   View source code 6 votes vote down vote up
@Override
public MetaDataInfo isFilteredOutMetaData(AttributeMetaData attribute, ParameterHandler handler)
		throws ConditionCreationException {
	try {
		if (attribute.getName().matches(attributeNameRegexp)) {
			if (exceptRegexp != null) {
				if (attribute.getName().matches(exceptRegexp)) {
					return MetaDataInfo.YES;
				} else {
					return MetaDataInfo.NO;
				}
			}
			return MetaDataInfo.NO;
		} else {
			return MetaDataInfo.YES;
		}
	} catch (PatternSyntaxException e) {
		return MetaDataInfo.UNKNOWN;
	}
}
 
Example 17
Project: V8LogScanner   File: CmdAddRgx.java   View source code 6 votes vote down vote up
@Override
public void execute() {
    V8LogScannerAppl appl = V8LogScannerAppl.instance();
    String[] message = {"input regular expression:"};
    String userInput = appl.getConsole().askInput(
            message,
            n -> {
                try {
                    Pattern.compile(n);
                } catch (PatternSyntaxException e) {
                    // incorrect expression
                    return false;
                }
                return true;
            }
            , true);

    if (userInput == null) {
        return;
    }
    appl.profile.setRgxExp(userInput);
}
 
Example 18
Project: lazycat   File: ExpressionParseTree.java   View source code 6 votes vote down vote up
protected int compareBranches() {
	String val1 = ((StringNode) left).getValue();
	String val2 = ((StringNode) right).getValue();

	int val2Len = val2.length();
	if (val2Len > 1 && val2.charAt(0) == '/' && val2.charAt(val2Len - 1) == '/') {
		// Treat as a regular expression
		String expr = val2.substring(1, val2Len - 1);
		try {
			Pattern pattern = Pattern.compile(expr);
			// Regular expressions will only ever be used with EqualNode
			// so return zero for equal and non-zero for not equal
			if (pattern.matcher(val1).find()) {
				return 0;
			} else {
				return -1;
			}
		} catch (PatternSyntaxException pse) {
			ssiMediator.log("Invalid expression: " + expr, pse);
			return 0;
		}
	}
	return val1.compareTo(val2);
}
 
Example 19
Project: OpenDiabetes   File: SqlFile.java   View source code 6 votes vote down vote up
/**
 * Search Command History for a regex match.
 *
 * @return Absolute command number, if any match.
 */
private Integer historySearch(String findRegex) throws BadSpecial {
    if (history == null)
        throw new BadSpecial(SqltoolRB.history_unavailable.getString());
    Pattern pattern = null;
    try {
        pattern = Pattern.compile("(?ims)" + findRegex);
    } catch (PatternSyntaxException pse) {
        throw new BadSpecial(SqltoolRB.regex_malformat.getString(pse));
    }
    // Make matching more liberal.  Users can customize search behavior
    // by using "(?-OPTIONS)" or (?OPTIONS) in their regexes.
    for (int index = history.size() - 1; index >= 0; index--)
        if (pattern.matcher((history.get(index)).val).find())
            return Integer.valueOf(index + oldestHist);
    return null;
}
 
Example 20
Project: CSipSimple   File: Filter.java   View source code 6 votes vote down vote up
private boolean patternMatches(Context ctxt, String number, Bundle extraHdr, boolean defaultValue) {
    if(CALLINFO_AUTOREPLY_MATCHER_KEY.equals(matchPattern)) {
        if(extraHdr != null &&
               extraHdr.containsKey("Call-Info")) {
               String hdrValue = extraHdr.getString("Call-Info");
               if(hdrValue != null) {
                   hdrValue = hdrValue.trim();
               }
               if(!TextUtils.isEmpty(hdrValue) &&
                       "answer-after=0".equalsIgnoreCase(hdrValue)){
                   return true;
               }
           }
    }else if(BLUETOOTH_MATCHER_KEY.equals(matchPattern)) {
           return BluetoothWrapper.getInstance(ctxt).isBTHeadsetConnected();
       }else {
           try {
               return Pattern.matches(matchPattern, number);
           }catch(PatternSyntaxException e) {
               logInvalidPattern(e);
           }
       }
    return defaultValue;
}
 
Example 21
Project: xdman   File: VMSVersioningFTPEntryParser.java   View source code 6 votes vote down vote up
/**
  * This constructor allows the creation of a VMSVersioningFTPEntryParser
  * object with something other than the default configuration.
  *
  * @param config The {@link FTPClientConfig configuration} object used to
  * configure this parser.
  * @exception IllegalArgumentException
  * Thrown if the regular expression is unparseable.  Should not be seen
  * under normal conditions.  It it is seen, this is a sign that
  * <code>REGEX</code> is  not a valid regular expression.
  * @since 1.4
  */
 public VMSVersioningFTPEntryParser(FTPClientConfig config)
 {
     super();
     configure(config);
     try
     {
         //_preparse_matcher_ = new Perl5Matcher();
         _preparse_pattern_ = Pattern.compile(PRE_PARSE_REGEX);
     }
     catch (PatternSyntaxException pse)
     {
         throw new IllegalArgumentException (
             "Unparseable regex supplied:  " + PRE_PARSE_REGEX);
     }

}
 
Example 22
Project: directory-ldap-api   File: TelephoneNumberSyntaxChecker.java   View source code 6 votes vote down vote up
/**
 * Set the default regular expression for the Telephone number
 * 
 * @param regexp the default regular expression.
 */
public Builder setDefaultRegexp( String regexp )
{
    defaultRegexp = regexp;
    
    try
    {
        defaultPattern = Pattern.compile( regexp );
    }
    catch ( PatternSyntaxException pse )
    {
        // Roll back to the default pattern
        defaultPattern = Pattern.compile( DEFAULT_REGEXP );
    }

    return this;
}
 
Example 23
Project: alfresco-repository   File: RegexHomeFolderProvider.java   View source code 6 votes vote down vote up
private Pattern getPattern(String patternString)
{
    if (patternString == null || patternString.trim().length() == 0)
        return null;
    
    Pattern pattern;
    try
    {
        pattern = Pattern.compile(patternString);
        logger.debug("Successfully compiled patternString : " + patternString);
    } catch (PatternSyntaxException pse)
    {
        throw new PersonException("Pattern string :" + patternString + " does not compile", pse);
    }
    return pattern;
}
 
Example 24
Project: DiscordSelfBlueBot   File: CommandParser.java   View source code 6 votes vote down vote up
public CommandContainer parse(String str, MessageReceivedEvent event) {
    ArrayList<String> split = new ArrayList<String>();
    String raw = str;
    String noprefix;
    try {
        noprefix = raw.replaceFirst(SelfBot.getPrefix(), "");
    } catch (PatternSyntaxException e) {
        noprefix = raw.replaceFirst("\\" + SelfBot.getPrefix(), "");
    }
    String[] split_noprefix = noprefix.split(" ");
    for(String s: split_noprefix) {split.add(s);}
    String invoke = split.get(0);
    String[] args = new String[split.size() -1];
    split.subList(1, split.size()).toArray(args);

    return new CommandContainer(raw, noprefix, split_noprefix, invoke, args, event);
}
 
Example 25
Project: tomcat7   File: ReplicationValve.java   View source code 6 votes vote down vote up
/**
 * compile filter string to regular expression
 * @see Pattern#compile(java.lang.String)
 * @param filter
 *            The filter to set.
 */
public void setFilter(String filter) {
    if (log.isDebugEnabled())
        log.debug(sm.getString("ReplicationValve.filter.loading", filter));
    
    if (filter == null || filter.length() == 0) {
        this.filter = null;
    } else {
        try {
            this.filter = Pattern.compile(filter);
        } catch (PatternSyntaxException pse) {
            log.error(sm.getString("ReplicationValve.filter.failure",
                    filter), pse);
        }
    }
}
 
Example 26
Project: burpextender-proxyhistory-webui   File: GUIConfig.java   View source code 5 votes vote down vote up
public static boolean isValidRegexpPattern(String p) {
    if (null == p) {
        return false;
    }
    try {
        Pattern.compile(p);
        return true;
    } catch (PatternSyntaxException e) {
        return false;
    }
}
 
Example 27
Project: openjdk-jdk10   File: JdkRegExp.java   View source code 5 votes vote down vote up
/**
 * Construct a Regular expression from the given {@code source} and {@code flags} strings.
 *
 * @param source RegExp source string
 * @param flags RegExp flag string
 * @throws ParserException if flags is invalid or source string has syntax error.
 */
public JdkRegExp(final String source, final String flags) throws ParserException {
    super(source, flags);

    int intFlags = 0;

    if (isIgnoreCase()) {
        intFlags |= CASE_INSENSITIVE | UNICODE_CASE;
    }
    if (isMultiline()) {
        intFlags |= MULTILINE;
    }

    try {
        RegExpScanner parsed;

        try {
            parsed = RegExpScanner.scan(source);
        } catch (final PatternSyntaxException e) {
            // refine the exception with a better syntax error, if this
            // passes, just rethrow what we have
            Pattern.compile(source, intFlags);
            throw e;
        }

        if (parsed != null) {
            this.pattern = Pattern.compile(parsed.getJavaPattern(), intFlags);
            this.groupsInNegativeLookahead = parsed.getGroupsInNegativeLookahead();
        }
    } catch (final PatternSyntaxException e2) {
        throwParserException("syntax", e2.getMessage());
    }
}
 
Example 28
Project: lazycat   File: ReplicationValve.java   View source code 5 votes vote down vote up
/**
 * compile filter string to regular expression
 * 
 * @see Pattern#compile(java.lang.String)
 * @param filter
 *            The filter to set.
 */
public void setFilter(String filter) {
	if (log.isDebugEnabled())
		log.debug(sm.getString("ReplicationValve.filter.loading", filter));

	if (filter == null || filter.length() == 0) {
		this.filter = null;
	} else {
		try {
			this.filter = Pattern.compile(filter);
		} catch (PatternSyntaxException pse) {
			log.error(sm.getString("ReplicationValve.filter.failure", filter), pse);
		}
	}
}
 
Example 29
Project: NoteBuddy   File: DirectoryReader.java   View source code 5 votes vote down vote up
/**
 * This method returns a list of all files
 * @param folder
 * @param sort
 * @return
 * @throws PatternSyntaxException
 */
@Nullable
public static List<String> getFileNames(final String folder, final int sort) throws PatternSyntaxException
{
    File fileDir = new File(folder);
    if(!fileDir.exists() || !fileDir.isDirectory()){
        return null;
    }

    String[] files = fileDir.list();
    if(files.length == 0){
        return null;
    }

    List<String> storedData = new ArrayList<String>();
    for(String file : files) {
        if(!file.contains("notebuddy") && !file.contains("yoerinijs")) {
            storedData.add(file);
        }
    }
    if(storedData.size() == 0) {
        return null;
    }
    if (sort != 0)
    {
        Collections.sort(storedData, String.CASE_INSENSITIVE_ORDER);
        if (sort < 0)
            Collections.reverse(storedData);
    }
    return storedData;
}
 
Example 30
Project: yacy_grid_mcp   File: Domains.java   View source code 5 votes vote down vote up
public static List<Pattern> makePatterns(final String patternList) throws PatternSyntaxException {
    final String[] entries = (patternList != null) ? CommonPattern.COMMA.split(patternList) : new String[0];
    final List<Pattern> patterns = new ArrayList<Pattern>(entries.length);
    for (final String entry : entries) {
        patterns.add(Pattern.compile(entry.trim()));
    }
    return patterns;
}
 
Example 31
Project: pgcodekeeper   File: DiffTableViewer.java   View source code 5 votes vote down vote up
public void setFilter(String value) {
    if (value == null || value.isEmpty()) {
        filterName = null;
        regExPattern = null;
    } else {
        filterName = value.toLowerCase();
        try {
            regExPattern = Pattern.compile(value, Pattern.CASE_INSENSITIVE);
        } catch (PatternSyntaxException e) {
            regExPattern = null;
        }
    }
}
 
Example 32
Project: dswork   File: Element.java   View source code 5 votes vote down vote up
public List<Element> getElementsByAttributeValueMatching(String key, String regex)
{
	Pattern pattern;
	try
	{
		pattern = Pattern.compile(regex);
	}
	catch(PatternSyntaxException e)
	{
		throw new IllegalArgumentException("Pattern syntax error: " + regex, e);
	}
	return getElementsByAttributeValueMatching(key, pattern);
}
 
Example 33
Project: athena   File: PatternRestrictionListener.java   View source code 5 votes vote down vote up
/**
 * Validates and return the valid pattern.
 *
 * @param ctx context object of the grammar rule
 * @return validated string
 */
private static String getValidPattern(GeneratedYangParser.PatternStatementContext ctx) {
    String userInputPattern = ctx.string().getText().replace("\"", EMPTY_STRING);
    try {
        Pattern.compile(userInputPattern);
    } catch (PatternSyntaxException exception) {
        ParserException parserException = new ParserException("YANG file error : " +
                YangConstructType.getYangConstructType(PATTERN_DATA) + " name " + ctx.string().getText() +
                " is not a valid regular expression");
        parserException.setLine(ctx.getStart().getLine());
        parserException.setCharPosition(ctx.getStart().getCharPositionInLine());
        throw parserException;
    }
    return userInputPattern;
}
 
Example 34
Project: hadoop   File: TestGlobPattern.java   View source code 5 votes vote down vote up
private void shouldThrow(String... globs) {
  for (String glob : globs) {
    try {
      GlobPattern.compile(glob);
    }
    catch (PatternSyntaxException e) {
      e.printStackTrace();
      continue;
    }
    assertTrue("glob "+ glob +" should throw", false);
  }
}
 
Example 35
Project: LeCatApp   File: Util.java   View source code 5 votes vote down vote up
public static String stringFilterForLetterNdNumber(String str)throws PatternSyntaxException{
    // 只允许字母和数字
    String   regEx  =  "[^a-zA-Z0-9]";
    Pattern   p   =   Pattern.compile(regEx);
    Matcher   m   =   p.matcher(str);
    return   m.replaceAll("").trim();
}
 
Example 36
Project: SleepOnLan   File: Commander.java   View source code 5 votes vote down vote up
private void cmdSplit(String cmd){
	
	try {
		cmds = cmd.split("\\n+");
	} catch (PatternSyntaxException e) {
		e.printStackTrace();
	}
	
}
 
Example 37
Project: openjdk-jdk10   File: SynthParser.java   View source code 5 votes vote down vote up
private void startBind(Attributes attributes) throws SAXException {
    ParsedSynthStyle style = null;
    String path = null;
    int type = -1;

    for(int i = attributes.getLength() - 1; i >= 0; i--) {
        String key = attributes.getQName(i);

        if (key.equals(ATTRIBUTE_STYLE)) {
            style = (ParsedSynthStyle)lookup(attributes.getValue(i),
                                              ParsedSynthStyle.class);
        }
        else if (key.equals(ATTRIBUTE_TYPE)) {
            String typeS = attributes.getValue(i).toUpperCase();

            if (typeS.equals("NAME")) {
                type = DefaultSynthStyleFactory.NAME;
            }
            else if (typeS.equals("REGION")) {
                type = DefaultSynthStyleFactory.REGION;
            }
            else {
                throw new SAXException("bind: unknown type " + typeS);
            }
        }
        else if (key.equals(ATTRIBUTE_KEY)) {
            path = attributes.getValue(i);
        }
    }
    if (style == null || path == null || type == -1) {
        throw new SAXException("bind: you must specify a style, type " +
                               "and key");
    }
    try {
        _factory.addStyle(style, path, type);
    } catch (PatternSyntaxException pse) {
        throw new SAXException("bind: " + path + " is not a valid " +
                               "regular expression");
    }
}
 
Example 38
Project: incubator-netbeans   File: RegexpUtil.java   View source code 5 votes vote down vote up
/**
 * Compile file name regular expression pattern, if it is not null. On
 * success, field fileNamePattern is set to newly compiled pattern.
 */
private static Pattern compileRegexpFileNamePattern(String expr)
        throws PatternSyntaxException {

    assert expr != null;
    return Pattern.compile(expr, Pattern.CASE_INSENSITIVE);
}
 
Example 39
Project: incubator-netbeans   File: RegexpUtil.java   View source code 5 votes vote down vote up
/**
 * Compile file name pattern for search options.
 *
 * @param searchScopeOptions Search scope options containing file name
 * pattern specification.
 * @return Pattern for matching file names or file paths.
 * @throws PatternSyntaxException Thrown if file name pattern is invalid.
 */
public static Pattern makeFileNamePattern(
        @NonNull SearchScopeOptions searchScopeOptions)
        throws PatternSyntaxException {

    Parameters.notNull("searchScopeOptions", searchScopeOptions);   //NOI18N
    if (searchScopeOptions.isRegexp()) {
        return compileRegexpFileNamePattern(searchScopeOptions.getPattern());
    } else {
        return compileSimpleFileNamePattern(searchScopeOptions.getPattern());
    }
}
 
Example 40
Project: Leanplum-Android-SDK   File: FileManager.java   View source code 5 votes vote down vote up
private static List<Pattern> compilePatterns(List<String> patterns) {
  if (patterns == null) {
    return new ArrayList<>(0);
  }
  List<Pattern> compiledPatterns = new ArrayList<>(patterns.size());
  for (String pattern : patterns) {
    try {
      compiledPatterns.add(Pattern.compile(pattern));
    } catch (PatternSyntaxException e) {
      Log.e("Ignoring malformed resource syncing pattern: \"" + pattern +
          "\". Patterns must be regular expressions.");
    }
  }
  return compiledPatterns;
}