List of usage examples for java.util.regex Pattern pattern
pattern
From source file:de.cosmocode.junit.Asserts.java
/** * Asserts that the input does not match the regex defined by the pattern. * // www .j a va 2s . c o m * Fails if pattern is null. * Fails if input is null. * Fails if input matches pattern. * * @param pattern the {@link Pattern} to check against * @param input the input to check */ public static void assertDoesNotMatch(Pattern pattern, CharSequence input) { if (pattern == null) { fail("Pattern must not be null"); } else if (input == null) { fail("Input must not be null"); } else { final boolean matches = pattern.matcher(input.toString()).matches(); assertFalse("'" + input + "' matches '" + pattern.pattern() + "'", matches); } }
From source file:de.cosmocode.junit.Asserts.java
/** * Asserts that the input matches the regex defined by the pattern. * //ww w . j av a2s. co m * Fails if pattern is null. * Fails if input is null. * Fails if input does not match pattern. * * @param pattern the {@link Pattern} to check against * @param input the input to check */ public static void assertMatches(Pattern pattern, CharSequence input) { if (pattern == null) { fail("Pattern must not be null"); } else if (input == null) { fail("Input must not be null"); } else { final boolean matches = pattern.matcher(input.toString()).matches(); assertTrue("'" + input + "' doesn't match '" + pattern.pattern() + "'", matches); } }
From source file:com.github.nlloyd.hornofmongo.util.BSONizer.java
@SuppressWarnings("deprecation") public static Object convertBSONtoJS(MongoScope mongoScope, Object bsonObject) { Object jsObject = null;//from ww w . j a va2 s . c om if (bsonObject instanceof List<?>) { List<?> bsonList = (List<?>) bsonObject; Scriptable jsArray = (Scriptable) MongoRuntime.call(new NewInstanceAction(mongoScope, bsonList.size())); int index = 0; for (Object bsonEntry : bsonList) { ScriptableObject.putProperty(jsArray, index, convertBSONtoJS(mongoScope, bsonEntry)); index++; } jsObject = jsArray; } else if (bsonObject instanceof BSONObject) { Scriptable jsObj = (Scriptable) MongoRuntime.call(new NewInstanceAction(mongoScope)); BSONObject bsonObj = (BSONObject) bsonObject; for (String key : bsonObj.keySet()) { Object value = convertBSONtoJS(mongoScope, bsonObj.get(key)); MongoRuntime.call(new JSPopulatePropertyAction(jsObj, key, value)); } jsObject = jsObj; } else if (bsonObject instanceof Symbol) { jsObject = ((Symbol) bsonObject).getSymbol(); } else if (bsonObject instanceof Date) { jsObject = MongoRuntime.call( new NewInstanceAction(mongoScope, "Date", new Object[] { ((Date) bsonObject).getTime() })); } else if (bsonObject instanceof Pattern) { Pattern regex = (Pattern) bsonObject; String source = regex.pattern(); String options = Bytes.regexFlags(regex.flags()); jsObject = MongoRuntime .call(new NewInstanceAction(mongoScope, "RegExp", new Object[] { source, options })); } else if (bsonObject instanceof org.bson.types.ObjectId) { jsObject = MongoRuntime.call(new NewInstanceAction(mongoScope, "ObjectId")); ((ObjectId) jsObject).setRealObjectId((org.bson.types.ObjectId) bsonObject); } else if (bsonObject instanceof org.bson.types.MinKey) { jsObject = MongoRuntime.call(new NewInstanceAction(mongoScope, "MinKey")); } else if (bsonObject instanceof org.bson.types.MaxKey) { jsObject = MongoRuntime.call(new NewInstanceAction(mongoScope, "MaxKey")); } else if (bsonObject instanceof com.mongodb.DBRef) { com.mongodb.DBRef dbRef = (com.mongodb.DBRef) bsonObject; Object id = convertBSONtoJS(mongoScope, dbRef.getId()); jsObject = MongoRuntime.call( new NewInstanceAction(mongoScope, "DBRef", new Object[] { dbRef.getCollectionName(), id })); } else if (bsonObject instanceof BSONTimestamp) { BSONTimestamp bsonTstamp = (BSONTimestamp) bsonObject; jsObject = MongoRuntime.call(new NewInstanceAction(mongoScope, "Timestamp", new Object[] { bsonTstamp.getTime(), bsonTstamp.getInc() })); } else if (bsonObject instanceof Long) { jsObject = MongoRuntime.call(new NewInstanceAction(mongoScope, "NumberLong")); ((NumberLong) jsObject).setRealLong((Long) bsonObject); } else if (bsonObject instanceof Integer) { jsObject = Double.valueOf((Integer) bsonObject); } else if (bsonObject instanceof Code) { jsObject = ((Code) bsonObject).getCode(); } else if (bsonObject instanceof byte[]) { jsObject = MongoRuntime.call(new NewInstanceAction(mongoScope, "BinData")); ((BinData) jsObject).setValues(0, (byte[]) bsonObject); } else if (bsonObject instanceof Binary) { jsObject = MongoRuntime.call(new NewInstanceAction(mongoScope, "BinData")); ((BinData) jsObject).setValues(((Binary) bsonObject).getType(), ((Binary) bsonObject).getData()); } else if (bsonObject instanceof UUID) { jsObject = MongoRuntime.call(new NewInstanceAction(mongoScope, "BinData")); UUID uuid = (UUID) bsonObject; ByteBuffer dataBuffer = ByteBuffer.allocate(16); // mongodb wire protocol is little endian dataBuffer.order(ByteOrder.LITTLE_ENDIAN); dataBuffer.putLong(uuid.getMostSignificantBits()); dataBuffer.putLong(uuid.getLeastSignificantBits()); ((BinData) jsObject).setValues(BSON.B_UUID, dataBuffer.array()); } else { jsObject = bsonObject; } return jsObject; }
From source file:jvmoptions.OptionAnalyzer.java
static Map<String, Map<String, String>> parse(Path hpp) { System.out.printf("process %s %n", hpp); String file = hpp.subpath(4, hpp.getNameCount()).toString().replace(File.separatorChar, '/'); try {/*from w w w . j a v a2s. c o m*/ String all = preprocess(hpp); String categories = "(?<kind>develop|develop_pd|product|product_pd|diagnostic|experimental|notproduct|manageable|product_rw|lp64_product)"; // detect Regex bugs. List<String> names = parseNames(all, categories); Set<String> nameSet = new HashSet<>(); Pattern descPtn = Pattern.compile("\"((\\\\\"|[^\"])+)\""); Pattern pattern = Pattern.compile(categories + "\\((?<type>\\w+?),[ ]*(?<name>\\w+)[ ]*(,[ ]*(?<default>[\\w ()\\-+/*.\"]+))?,[ ]*(?<desc>(" + descPtn.pattern() + "[ ]*)+)\\)"); Map<String, Map<String, String>> result = new HashMap<>(); int times = 0; for (Matcher matcher = pattern.matcher(all); matcher.find(); times++) { String name = matcher.group("name"); verify(names, nameSet, times, name); String def = Objects.toString(matcher.group("default"), ""); String d = matcher.group("desc"); StringBuilder desc = new StringBuilder(); for (Matcher m = descPtn.matcher(d); m.find();) { desc.append(m.group(1).replaceAll("\\\\", "")); } Map<String, String> m = new HashMap<>(); m.put("kind", matcher.group("kind")); m.put("type", matcher.group("type")); m.put("default", def); m.put("description", desc.toString()); m.put("file", file); result.put(name, m); } System.out.printf(" %s contains %d options%n", hpp, times); return result; } catch (IOException e) { throw new UncheckedIOException(e); } }
From source file:org.dataconservancy.dcs.integration.main.LineageIT.java
/** * Map the ID of the deposited DCS entity to its archived identity. * * @param depositedId the ID of the DCS entity in the deposited DCP package * @param info the DepositInfo, the result of a successful deposit * @return the archival ID of the DCS entity. * @throws IOException/*from w w w .ja v a 2 s . co m*/ */ private static String getDcsIdFromDepositedId(String depositedId, DepositInfo info) throws IOException { // <eventDetail>Assigned identifier 'http://localhost:8080/dcs/entity/4' to DeliverableUnit 'du/1'</eventDetail> Pattern p = Pattern.compile(".*<eventDetail>Assigned identifier '(.*)' to DeliverableUnit '" + depositedId + "'</eventDetail>.*"); String depositContent = IOUtils.toString(info.getDepositContent().getInputStream()); Matcher m = p.matcher(depositContent); assertTrue("Pattern '" + p.pattern() + "' didn't match '" + depositContent + "'", m.matches()); return m.group(1); }
From source file:org.fluentd.jvmwatcher.LocalJvmInfo.java
/** * @param shortName// w w w. java 2s.c om * @param patt */ public static void addTargetProcessPattern(String shortName, Pattern patt) { filterPassProcMap_.put(shortName, patt); log.info("add target process. shortname=" + shortName + " match pattern=" + patt.pattern()); }
From source file:com.logsniffer.util.grok.Grok.java
/** * Compiles a grok pattern and generates an internal standard pattern * representation for it.//from w w w .java2s . c o m * * @param registry * Groks registry for predefined types * @param pattern * the grok pattern * @param flags * flags corresponding to {@link Pattern#flags()} * @return a compiled grok pattern * @throws GrokException */ @SuppressWarnings("unchecked") public static Grok compile(final GroksRegistry registry, final String pattern, final int flags) throws GrokException { final Grok g = new Grok(); g.grokPattern = pattern; final StringBuilder compiledPattern = new StringBuilder(); final Matcher m = PATTERN_SUBGROK.matcher(pattern); int lastPos = 0; g.typeConverters = new HashMap<>(); while (m.find()) { final String left = pattern.substring(lastPos, m.start()); lastPos = m.end(); compiledPattern.append(left); int groupsCount = PatternHelper.countOpenParens(compiledPattern.toString(), compiledPattern.length()); final String subGrokName = m.group(1); final String subGrokAttr = m.group(2); String subGrokType = m.group(3); final Grok subGrok = registry.getGroks().get(subGrokName); if (subGrok == null) { throw new GrokException("No predefined Grok pattern for name '" + subGrokName + "' found used in pattern: " + pattern); } if (subGrokAttr != null) { compiledPattern.append("("); groupsCount++; g.groupNames.put(subGrokAttr, groupsCount); } if (subGrokType != null) { subGrokType = subGrokType.toLowerCase(); if (supportedTypeConverters.containsKey(subGrokType)) { g.typeConverters.put(groupsCount, (TypeConverter<Object>) supportedTypeConverters.get(subGrokType)); } else { LOGGER.warn("Conversion type {} not support in grok pattern: {}", subGrokType, m.group(0)); } } compiledPattern.append(subGrok.regexPattern.pattern()); if (subGrokAttr != null) { compiledPattern.append(")"); } for (final String subGrokSubAttr : subGrok.groupNames.keySet()) { final int subGrokGroup = subGrok.groupNames.get(subGrokSubAttr); g.groupNames.put(subGrokSubAttr, groupsCount + subGrokGroup); if (subGrok.typeConverters.get(subGrokGroup) != null) { g.typeConverters.put(groupsCount + subGrokGroup, subGrok.typeConverters.get(subGrokGroup)); } } } compiledPattern.append(pattern.substring(lastPos)); // g.regexPattern = Pattern.compile(compiledPattern.toString(), flags); final com.google.code.regexp.Pattern namedPattern = com.google.code.regexp.Pattern .compile(compiledPattern.toString(), flags); g.regexPattern = namedPattern.pattern(); for (final String name : namedPattern.groupInfo().keySet()) { g.groupNames.put(name, namedPattern.groupInfo().get(name).get(0).groupIndex() + 1); } // Order groups by occurrence final List<Entry<String, Integer>> groups = new ArrayList<>(g.groupNames.entrySet()); Collections.sort(groups, new Comparator<Entry<String, Integer>>() { @Override public int compare(final Entry<String, Integer> o1, final Entry<String, Integer> o2) { return o1.getValue().compareTo(o2.getValue()); } }); g.groupNames.clear(); for (final Entry<String, Integer> entry : groups) { g.groupNames.put(entry.getKey(), entry.getValue()); } LOGGER.debug("Compiled grok: {}", g); return g; }
From source file:org.fluentd.jvmwatcher.LocalJvmInfo.java
/** * @param checkJvm// w w w.j a v a 2 s. c o m * @return */ public static LocalJvmInfo isTargetProcess(LocalJvmInfo checkJvm) { LocalJvmInfo ret = null; /* * If the process name which is dealt with for the measurement isn't defining, * it makes a measurement object unconditionally. */ if (filterPassProcMap_.size() == 0) { return checkJvm; } // check process name for (Map.Entry<String, Pattern> elem : filterPassProcMap_.entrySet()) { String key = elem.getKey(); Pattern val = elem.getValue(); Matcher match = val.matcher(checkJvm.displayName_); // The process name which is dealt with for the measurement was found out. if (match.find()) { ret = checkJvm; checkJvm.setShortName(key); log.debug("match prosecc=" + val.pattern()); break; } else { log.debug("unmatch prosecc=" + val.pattern()); } } return ret; }
From source file:org.tinymediamanager.core.tvshow.TvShowEpisodeAndSeasonParser.java
public static String cleanEpisodeTitle(String titleToClean, String tvShowName) { String basename = FilenameUtils .getBaseName(ParserUtils.removeStopwordsAndBadwordsFromTvEpisodeName(titleToClean)); // parse foldername Pattern regex = Pattern.compile("(.*[\\/\\\\])"); Matcher m = regex.matcher(basename); if (m.find()) { basename = basename.replaceAll(regex.pattern(), ""); }// www . ja v a 2 s . c om basename = basename + " "; // remove show name if (tvShowName != null && !tvShowName.isEmpty()) { // remove string like tvshow name (440, 24, ...) basename = basename.replaceAll("(?i)^" + Pattern.quote(tvShowName) + "", ""); basename = basename.replaceAll("(?i) " + Pattern.quote(tvShowName) + " ", ""); } basename = basename.replaceFirst("\\.\\w{1,4}$", ""); // remove extension if 1-4 chars basename = basename.replaceFirst("[\\(\\[]\\d{4}[\\)\\]]", ""); // remove (xxxx) or [xxxx] as year return removeEpisodeVariantsFromTitle(basename); }
From source file:org.apache.roller.weblogger.util.Blacklist.java
/** Test String against the RegularExpression rules. */ private static boolean testRegExRules(String str, List regexRules) { boolean hit = false; Pattern testPattern = null; Iterator iter = regexRules.iterator(); while (iter.hasNext()) { testPattern = (Pattern) iter.next(); // want to see what it is matching on, but only in debug mode if (mLogger.isDebugEnabled()) { Matcher matcher = testPattern.matcher(str); if (matcher.find()) { mLogger.debug(matcher.group() + " matched by " + testPattern.pattern()); return true; }//from w w w .j a v a 2 s . c o m } else { if (testPattern.matcher(str).find()) { return true; } } } return hit; }