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: L2jBrasil   File: EnterWorld.java   Source Code and License 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 2
Project: L2jBrasil   File: CharacterCreate.java   Source Code and License 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 3
Project: incubator-netbeans   File: TextRegexpUtil.java   Source Code and License 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 4
Project: sponge   File: TriggersTestTemplate.java   Source Code and License 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 5
Project: incubator-netbeans   File: FileNameController.java   Source Code and License 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 6
Project: incubator-netbeans   File: SvnUtils.java   Source Code and License 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 7
Project: OpenJSharp   File: RegExpScanner.java   Source Code and License 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 8
Project: incubator-netbeans   File: ConstantNameOptions.java   Source Code and License 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 9
Project: incubator-netbeans   File: Patch.java   Source Code and License 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 10
Project: incubator-netbeans   File: JavadocSearchType.java   Source Code and License 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 11
Project: rapidminer   File: AggregationOperator.java   Source Code and License 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 12
Project: MaxSim   File: Properties.java   Source Code and License 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 13
Project: rapidminer   File: MidasRegexpAttributeFilter.java   Source Code and License 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 14
Project: V8LogScanner   File: CmdAddRgx.java   Source Code and License 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 15
Project: lazycat   File: ExpressionParseTree.java   Source Code and License 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 16
Project: OpenDiabetes   File: SqlFile.java   Source Code and License 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 17
Project: CSipSimple   File: Filter.java   Source Code and License 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 18
Project: xdman   File: VMSVersioningFTPEntryParser.java   Source Code and License 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 19
Project: directory-ldap-api   File: TelephoneNumberSyntaxChecker.java   Source Code and License 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 20
Project: alfresco-repository   File: RegexHomeFolderProvider.java   Source Code and License 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 21
Project: DiscordSelfBlueBot   File: CommandParser.java   Source Code and License 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 22
Project: tomcat7   File: ReplicationValve.java   Source Code and License 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 23
Project: burpextender-proxyhistory-webui   File: GUIConfig.java   Source Code and License 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 24
Project: openjdk-jdk10   File: JdkRegExp.java   Source Code and License 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 25
Project: L2J-Global   File: PetNameTable.java   Source Code and License 5 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 26
Project: cyberduck   File: PreferencesController.java   Source Code and License 5 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 27
Project: lazycat   File: ReplicationValve.java   Source Code and License 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 28
Project: NoteBuddy   File: DirectoryReader.java   Source Code and License 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 29
Project: apache-tomcat-7.0.73-with-comment   File: ExpressionParseTree.java   Source Code and License 5 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 30
Project: yacy_grid_mcp   File: Domains.java   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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;
}
 
Example 41
Project: sonar-css-plugin   File: LessVariableNamingConventionCheck.java   Source Code and License 5 votes vote down vote up
@Override
public void validateParameters() {
  try {
    Pattern.compile(format);
  } catch (PatternSyntaxException exception) {
    throw new IllegalStateException(paramsErrorMessage(), exception);
  }
}
 
Example 42
Project: graphouse   File: MetricTree.java   Source Code and License 5 votes vote down vote up
@VisibleForTesting
static PathMatcher createPathMatcher(String globPattern) {
    try {
        return FileSystems.getDefault().getPathMatcher("glob:" + globPattern);
    } catch (PatternSyntaxException e) {
        return null;
    }
}
 
Example 43
Project: OpenJSharp   File: JdkRegExp.java   Source Code and License 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 44
Project: LeCatApp   File: Util.java   Source Code and License 5 votes vote down vote up
public static String stringFilterForText(String str)throws PatternSyntaxException{
    // 只允许汉字
    String   regEx  =  "[^\u4E00-\u9FA5]";
    Pattern   p   =   Pattern.compile(regEx);
    Matcher   m   =   p.matcher(str);
    return   m.replaceAll("").trim();
}
 
Example 45
Project: parabuild-ci   File: AbstractReferenceCheck.java   Source Code and License 5 votes vote down vote up
/**
 * Set the ignore name format to the specified regular expression.
 * @param aFormat a <code>String</code> value
 * @throws ConversionException unable to parse aFormat
 */
public void setIgnoreName(String aFormat)
    throws ConversionException
{
    try {
        mIgnoreNameRegexp = Utils.getPattern(aFormat);
    }
    catch (PatternSyntaxException e) {
        throw new ConversionException("unable to parse " + aFormat, e);
    }
}
 
Example 46
Project: sonar-css-plugin   File: CustomFunctionNamingConventionCheck.java   Source Code and License 5 votes vote down vote up
@Override
public void validateParameters() {
  try {
    Pattern.compile(format);
  } catch (PatternSyntaxException exception) {
    throw new IllegalStateException(paramsErrorMessage(), exception);
  }
}
 
Example 47
Project: lams   File: JdkRegexpMethodPointcut.java   Source Code and License 5 votes vote down vote up
/**
 * Compiles the supplied {@code String[]} into an array of
 * {@link Pattern} objects and returns that array.
 */
private Pattern[] compilePatterns(String[] source) throws PatternSyntaxException {
	Pattern[] destination = new Pattern[source.length];
	for (int i = 0; i < source.length; i++) {
		destination[i] = Pattern.compile(source[i]);
	}
	return destination;
}
 
Example 48
Project: sonar-css-plugin   File: UnknownTypeSelectorCheck.java   Source Code and License 5 votes vote down vote up
@Override
public void validateParameters() {
  try {
    Pattern.compile(exclusions);
  } catch (PatternSyntaxException exception) {
    throw new IllegalStateException(paramsErrorMessage(), exception);
  }
}
 
Example 49
Project: incubator-netbeans   File: ModuleOptions.java   Source Code and License 5 votes vote down vote up
@NbBundle.Messages({
    "# {0} - regexp",
    "MSG_CantCompileRegex=Cannot understand regular expession ''{0}''"
})
private static Pattern[] findMatcher(Env env, String[] pattern) {
    Pattern[] arr = new Pattern[pattern.length];
    for (int i = 0; i < arr.length; i++) {
        try {
            arr[i] = Pattern.compile(pattern[i]);
        } catch (PatternSyntaxException e) {
            env.getErrorStream().println(Bundle.MSG_CantCompileRegex(pattern[i]));
        }
    }
    return arr;
}
 
Example 50
Project: sonar-css-plugin   File: CommentRegularExpressionCheck.java   Source Code and License 5 votes vote down vote up
@Override
public void validateParameters() {
  try {
    Pattern.compile(regularExpression);
  } catch (PatternSyntaxException exception) {
    throw new IllegalStateException(paramsErrorMessage(), exception);
  }
}
 
Example 51
Project: sonar-css-plugin   File: FunctionRegularExpressionCheck.java   Source Code and License 5 votes vote down vote up
@Override
public void validateParameters() {
  try {
    Pattern.compile(regularExpression);
  } catch (PatternSyntaxException exception) {
    throw new IllegalStateException(paramsErrorMessage(), exception);
  }
}
 
Example 52
Project: NetDiscovery   File: ReplaceSelector.java   Source Code and License 5 votes vote down vote up
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);
    }
}
 
Example 53
Project: lams   File: Http11AprProcessor.java   Source Code and License 5 votes vote down vote up
/**
 * Add user-agent for which gzip compression didn't works
 * The user agent String given will be exactly matched
 * to the user-agent header submitted by the client.
 *
 * @param userAgent user-agent string
 */
public void addNoCompressionUserAgent(String userAgent) {
    try {
        Pattern nRule = Pattern.compile(userAgent);
        noCompressionUserAgents =
            addREArray(noCompressionUserAgents, nRule);
    } catch (PatternSyntaxException pse) {
        log.error(sm.getString("http11processor.regexp.error", userAgent), pse);
    }
}
 
Example 54
Project: monarch   File: Configuration.java   Source Code and License 5 votes vote down vote up
/**
 * Get the value of the <code>name</code> property as a <code>Pattern</code>. If no such property
 * is specified, or if the specified value is not a valid <code>Pattern</code>, then
 * <code>DefaultValue</code> is returned.
 *
 * @param name property name
 * @param defaultValue default value
 * @return property value as a compiled Pattern, or defaultValue
 */
public Pattern getPattern(String name, Pattern defaultValue) {
  String valString = get(name);
  if (null == valString || "".equals(valString)) {
    return defaultValue;
  }
  try {
    return Pattern.compile(valString);
  } catch (PatternSyntaxException pse) {
    LOG.warn("Regular expression '" + valString + "' for property '" + name
        + "' not valid. Using default", pse);
    return defaultValue;
  }
}
 
Example 55
Project: L2J-Global   File: L2VillageMasterInstance.java   Source Code and License 5 votes vote down vote up
private static boolean isValidName(String name)
{
	Pattern pattern;
	try
	{
		pattern = Pattern.compile(Config.CLAN_NAME_TEMPLATE);
	}
	catch (PatternSyntaxException e)
	{
		_log.warning("ERROR: Wrong pattern for clan name!");
		pattern = Pattern.compile(".*");
	}
	return pattern.matcher(name).matches();
}
 
Example 56
Project: rapidminer   File: Finds.java   Source Code and License 5 votes vote down vote up
@Override
protected Boolean compute(String value1, String value2) {
	if (value1 == null || value2 == null) {
		return null;
	}
	try {
		return value1.matches(".*" + value2 + ".*");
	} catch (PatternSyntaxException e) {
		throw new FunctionInputException("process.error.invalid_regex", value2);
	}
}
 
Example 57
Project: Spring-Shiro-Spark   File: RegsUtil.java   Source Code and License 5 votes vote down vote up
public static boolean checkSpecialChar(String str) throws PatternSyntaxException {
    // 清除掉所有特殊字符
    String regEx = ".*[`[email protected]#$%^&*()+=|{}':;',\\[\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?\\\\]+.*";
    Pattern p = Pattern.compile(regEx);
    Matcher m = p.matcher(str);
    return m.matches();
}
 
Example 58
Project: springboot-shiro-cas-mybatis   File: RegisteredServiceEditBean.java   Source Code and License 5 votes vote down vote up
/**
 * Determine service type by pattern.
 *
 * @param pattern the pattern
 * @return the abstract registered service
 */
private boolean isValidRegex(final String pattern) {
    try {
        Pattern.compile(serviceId);
        LOGGER.debug("Pattern is a valid regex.", pattern);
        return true;
    } catch (final PatternSyntaxException exception) {
        return false;
    }
}
 
Example 59
Project: butterfly   File: RegexMatchTest.java   Source Code and License 5 votes vote down vote up
@Test
public void evalInvalidRegexTest() {
    RegexMatch regexMatch;
    TUExecutionResult executionResult;

    regexMatch = new RegexMatch().relative("/src/main/resources/dogs.yaml");
    regexMatch.setRegex("*Mustache*");
    executionResult = regexMatch.execution(transformedAppFolder, transformationContext);
    Assert.assertEquals(executionResult.getType(), TUExecutionResult.Type.ERROR);
    Assert.assertNull(executionResult.getValue());
    Assert.assertEquals(executionResult.getException().getClass(), PatternSyntaxException.class);
    Assert.assertEquals(executionResult.getException().getMessage(), "Dangling meta character '*' near index 0\n*Mustache*\n^");
}
 
Example 60
Project: jdk8u-jdk   File: Basic.java   Source Code and License 5 votes vote down vote up
static void assertBadPattern(String path, String pattern) {
    System.out.format("Compile bad pattern %s\t", pattern);
    try {
        FileSystems.getDefault().getPathMatcher("glob:" + pattern);
        System.out.println("Compiled ==> UNEXPECTED RESULT!");
        failures++;
    } catch (PatternSyntaxException e) {
        System.out.println("Failed to compile ==> OKAY");
    }
}