Here are the examples of the java api class java.util.regex.Pattern taken from open source projects.
1. GroupCounts#testPatternCompileGroupCount()
View licensevoid testPatternCompileGroupCount(@Regex String r, @Regex(3) String r3, @Regex(5) String r5) { @Regex(5) Pattern p1 = Pattern.compile(r5); @Regex Pattern p2 = Pattern.compile(r5); @Regex Pattern p3 = Pattern.compile(r); //:: error: (assignment.type.incompatible) // error @Regex(6) Pattern p4 = Pattern.compile(r5); //:: error: (assignment.type.incompatible) // error @Regex(6) Pattern p5 = Pattern.compile(r3); // Make sure Pattern.compile still works when passed an @Unqualified String // that's actually a regex, with the warning suppressed. @SuppressWarnings("regex:argument.type.incompatible") Pattern p6 = Pattern.compile("(" + r + ")"); }
2. SchemaSamplerTest#testSeveral()
View license@Test public void testSeveral() throws IOException { SchemaSampler s = new SchemaSampler(Resources.asCharSource(Resources.getResource("schema003.json"), Charsets.UTF_8).read()); Multiset<String> gender = HashMultiset.create(); Pattern namePattern = Pattern.compile("[A-Z][a-z]+ [A-Z][a-z]+"); Pattern addressPattern = Pattern.compile("[0-9]+ [A-Z][a-z]+ [A-Z][a-z]+ [A-Z][a-z]+"); Pattern datePattern1 = Pattern.compile("[01][0-9]/[0123][0-9]/20[012][0-9]"); Pattern datePattern2 = Pattern.compile("2014-0[12]-[0123][0-9]"); Pattern datePattern3 = Pattern.compile("[01][0-9]/[0123][0-9]/199[5-9]"); for (int i = 0; i < 10000; i++) { JsonNode record = s.sample(); assertEquals(i, record.get("id").asInt()); assertTrue(namePattern.matcher(record.get("name").asText()).matches()); assertTrue(addressPattern.matcher(record.get("address").asText()).matches()); assertTrue(datePattern1.matcher(record.get("first_visit").asText()).matches()); assertTrue(datePattern2.matcher(record.get("second_date").asText()).matches()); assertTrue(datePattern3.matcher(record.get("third_date").asText()).matches()); gender.add(record.get("gender").asText()); } check(gender, 0.5 * (1 - 0.02), "MALE"); check(gender, 0.5 * (1 - 0.02), "FEMALE"); check(gender, 0.02 * (1 - 0.02), "OTHER"); }
3. StdColorUtil#formatColor()
View licensepublic static String formatColor(String color) { Pattern RRGGBB = Pattern.compile("#[0-9A-Fa-f]{6}"); Pattern RGB = Pattern.compile("#[0-9A-Fa-f]{3}"); Pattern rgb = Pattern.compile("[rgb(d+,d+,d+)]"); Pattern rgb2 = Pattern.compile("[rgb(d+%,d+%,d+%)]"); if (RRGGBB.matcher(color).find()) { return color.toUpperCase(); } else if (RGB.matcher(color).find()) { String r = "#" + color.charAt(1) + color.charAt(1) + color.charAt(2) + color.charAt(2) + color.charAt(3) + color.charAt(3); return r.toUpperCase(); } else if (rgb2.matcher(color).find() && color.contains("%")) { String[] rgbCls = color.trim().replace("rgb(", "").replace(")", "").replace("%", "").split(","); String r = "#" + percent2HEX(rgbCls[0]) + percent2HEX(rgbCls[1]) + percent2HEX(rgbCls[2]); return r.toUpperCase(); } else if (rgb.matcher(color).find() && color.contains("rgb")) { String[] rgbCls = color.trim().replace("rgb(", "").replace(")", "").split(","); String r = "#" + DEC2HEX(rgbCls[0]) + DEC2HEX(rgbCls[1]) + DEC2HEX(rgbCls[2]); return r.toUpperCase(); } else { return getColorRGB(color); } }
4. JavacErrorParser#getMissingSymbolFromCompilerError()
View licensepublic Optional<String> getMissingSymbolFromCompilerError(String error) { for (Pattern pattern : onePartPatterns) { Matcher matcher = pattern.matcher(error); if (matcher.find()) { return Optional.of(matcher.group("symbol")); } } for (Pattern pattern : twoPartPatterns) { Matcher matcher = pattern.matcher(error); if (matcher.find()) { return Optional.of(matcher.group("package") + "." + matcher.group("class")); } } for (Pattern pattern : localPackagePatterns) { Matcher matcher = pattern.matcher(error); if (matcher.find()) { return getMissingSymbolInLocalPackage(matcher); } } return Optional.absent(); }
5. HierarchicalProperties#replacePlaceholders()
View licenseprivate void replacePlaceholders() { Pattern systemProperty = Pattern.compile("\\$\\{system\\.([^\\}]+)\\}"); Pattern environmentVariable = Pattern.compile("\\$\\{env\\.([^\\}]+)\\}"); Pattern localPlaceholder = Pattern.compile("\\$\\{([^\\}]+)\\}"); for (Iterator it = hierarchicalMap.values().iterator(); it.hasNext(); ) { Map properties = ((ChainedMap) it.next()).child; for (Iterator it1 = properties.entrySet().iterator(); it1.hasNext(); ) { Map.Entry e = (Map.Entry) it1.next(); // /!\ replacement values themselves might contain placeholders. So always retrieve the value from the map entry e.setValue(SystemUtils.replaceProperties((String) e.getValue(), localPlaceholder, getRootMap().child)); e.setValue(SystemUtils.replaceProperties((String) e.getValue(), systemProperty, System.getProperties())); e.setValue(SystemUtils.replaceProperties((String) e.getValue(), environmentVariable, System.getenv())); } } }
6. FormattedSqlChangeLogParser#parseSqlCheckCondition()
View licenseprivate SqlPrecondition parseSqlCheckCondition(String body) throws ChangeLogParseException { Pattern[] patterns = new Pattern[] { Pattern.compile("^(?:expectedResult:)?(\\w+) (.*)", Pattern.CASE_INSENSITIVE), Pattern.compile("^(?:expectedResult:)?'([^']+)' (.*)", Pattern.CASE_INSENSITIVE), Pattern.compile("^(?:expectedResult:)?\"([^\"]+)\" (.*)", Pattern.CASE_INSENSITIVE) }; for (Pattern pattern : patterns) { Matcher matcher = pattern.matcher(body); if (matcher.matches() && matcher.groupCount() == 2) { SqlPrecondition p = new SqlPrecondition(); p.setExpectedResult(matcher.group(1)); p.setSql(matcher.group(2)); return p; } } throw new ChangeLogParseException("Could not parse a SqlCheck precondition from '" + body + "'."); }
7. SimpleTaggerWithConstraints#getCRF()
View licensepublic static CRF getCRF(InstanceList training, int[] orders, String defaultLabel, String forbidden, String allowed, boolean connected) { Pattern forbiddenPat = Pattern.compile(forbidden); Pattern allowedPat = Pattern.compile(allowed); CRF crf = new CRF(training.getPipe(), (Pipe) null); String startName = crf.addOrderNStates(training, orders, null, defaultLabel, forbiddenPat, allowedPat, connected); for (int i = 0; i < crf.numStates(); i++) crf.getState(i).setInitialWeight(Transducer.IMPOSSIBLE_WEIGHT); crf.getState(startName).setInitialWeight(0.0); crf.setWeightsDimensionDensely(); return crf; }
8. HTMLDecoder#decode()
View licensepublic static String decode(String html) { TextEditor ed = new TextEditor(html); Pattern p1 = Pattern.compile("&#(\\d+);"); ed.replaceAll(p1, new Replacement() { public String replacement(Matcher m) { String charDecimal = m.group(1); char ch = (char) Integer.parseInt(charDecimal); return Character.toString(ch); } }); Pattern p2 = Pattern.compile("&#x([0-9a-fA-F]+);"); ed.replaceAll(p2, new Replacement() { public String replacement(Matcher m) { String charHex = m.group(1); char ch = (char) Integer.parseInt(charHex, 16); return Character.toString(ch); } }); return ed.toString(); }
9. IntrospectorDumperClassPoolVisitor#filter()
View licensepublic boolean filter(String className) { if (className.indexOf('.') == -1) { return false; } boolean inIncludes = false; for (Pattern include : includes) { if (include.matcher(className).find()) { inIncludes = true; break; } } if (!inIncludes) { return false; } for (Pattern exclude : excludes) { if (exclude.matcher(className).find()) { return false; } } return true; }
10. MotifFinderSource#getMatcher()
View license/** * See {@link #search(String, Strand, String, int, byte[])} for explanation of parameters * @param pattern * @param strand * @param sequence * @return */ static Matcher getMatcher(String pattern, Strand strand, byte[] sequence) { byte[] seq = sequence; if (strand == Strand.NEGATIVE) { //sequence could be quite long, cloning it might take up a lot of memory //and is un-necessary if we are careful. //seq = seq.clone(); SequenceUtil.reverseComplement(seq); } Pattern regex = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE); String stringSeq = new String(seq); return regex.matcher(stringSeq); }
11. FilterPattern#methodMatches()
View licensepublic boolean methodMatches(@NotNull PsiMethod method) { final String methodName = method.getName(); final Pattern methodNamePattern = getMethodNamePattern(); if ((methodNamePattern != null) && methodNamePattern.matcher(methodName).matches()) { return true; } final PsiType returnType = method.getReturnType(); if (returnType == null) { return false; } final Pattern patternTypePattern = getMethodTypePattern(); final String methodType = returnType.getCanonicalText(); return (patternTypePattern != null) && methodTypePattern.matcher(methodType).matches(); }
12. AbstractExternalFilter#getParseSettings()
View license@NotNull protected ParseSettings getParseSettings(@NotNull String url) { Pattern startSection = ourClassDataStartPattern; Pattern endSection = ourClassDataEndPattern; boolean anchorPresent = false; Matcher anchorMatcher = ourAnchorSuffix.matcher(url); if (anchorMatcher.find()) { anchorPresent = true; startSection = Pattern.compile(Pattern.quote("<a name=\"" + anchorMatcher.group(1) + "\""), Pattern.CASE_INSENSITIVE); endSection = ourNonClassDataEndPattern; } return new ParseSettings(startSection, endSection, !anchorPresent, anchorPresent); }
13. MavenUtil#isIncluded()
View licensepublic static boolean isIncluded(String relativeName, List<Pattern> includes, List<Pattern> excludes) { boolean result = false; for (Pattern each : includes) { if (each.matcher(relativeName).matches()) { result = true; break; } } if (!result) return false; for (Pattern each : excludes) { if (each.matcher(relativeName).matches()) return false; } return true; }
14. CmsHtmlImportConverter#extractHtml()
View license/** * Extracts the content of a HTML page.<p> * * This method should be pretty robust and work even if the input HTML does not contains * the specified matchers.<p> * * @param content the content to extract the body from * @param startpoint the point where matching starts * @param endpoint the point where matching ends * @return the extracted body tag content */ public static String extractHtml(String content, String startpoint, String endpoint) { /** Regex that matches a start body tag. */ Pattern startPattern = Pattern.compile(startpoint, Pattern.CASE_INSENSITIVE); /** Regex that matches an end body tag. */ Pattern endPattern = Pattern.compile(endpoint, Pattern.CASE_INSENSITIVE); Matcher startMatcher = startPattern.matcher(content); Matcher endMatcher = endPattern.matcher(content); int start = 0; int end = content.length(); if (startMatcher.find()) { start = startMatcher.end(); } if (endMatcher.find(start)) { end = endMatcher.start(); } return content.substring(start, end); }
15. AcknowledgeMessage#parsePayLoad()
View license@Override protected void parsePayLoad() { Pattern SHORT_RESPONSE_PATTERN = Pattern.compile("(\\w{4})"); Pattern EXTENDED_RESPONSE_PATTERN = Pattern.compile("(\\w{4})(\\w{16})"); Matcher shortMatcher = SHORT_RESPONSE_PATTERN.matcher(payLoad); Matcher extendedMatcher = EXTENDED_RESPONSE_PATTERN.matcher(payLoad); if (extendedMatcher.matches()) { code = ExtensionCode.forValue(Integer.parseInt(extendedMatcher.group(1), 16)); if (code == null) { code = ExtensionCode.UNKNOWN; } extendedMAC = extendedMatcher.group(2); } else if (shortMatcher.matches()) { code = ExtensionCode.forValue(Integer.parseInt(shortMatcher.group(1), 16)); if (code == null) { code = ExtensionCode.UNKNOWN; } } else { logger.debug("Plugwise protocol AcknowledgeMessage error: {} does not match", payLoad); code = ExtensionCode.UNKNOWN; } }
16. Verifier#verifyUncommonTrapFired()
View licenseprivate static void verifyUncommonTrapFired(Properties properties, List<String> compLogContent) { String firedTrapRE = String.format(FIRED_TRAP_PATTERN, properties.getProperty(UNCOMMON_TRAP_NAME, ".*"), properties.getProperty(UNCOMMON_TRAP_ACTION, ".*")); String jvmsRE = String.format(JVMS_PATTERN, properties.getProperty(UNCOMMON_TRAP_BCI, ".*")); boolean trapFired = false; Pattern firedTrapPattern = Pattern.compile(firedTrapRE); Pattern jvmsPattern = Pattern.compile(jvmsRE); Iterator<String> iterator = compLogContent.iterator(); while (iterator.hasNext() && !trapFired) { trapFired = firedTrapPattern.matcher(iterator.next()).find() && jvmsPattern.matcher(iterator.next()).find(); } boolean shouldBeFired = Boolean.valueOf(properties.getProperty(UNCOMMON_TRAP_SHOULD_FIRED)); Asserts.assertEQ(shouldBeFired, trapFired, String.format("Uncommon trap that matches following string in compilation log" + " should %sbe fired: %s.", (shouldBeFired ? "" : "not "), firedTrapRE)); }
17. MaxWarns#check()
View licensevoid check(String out, int count) { System.err.println(out); Pattern warn = Pattern.compile("warning - @param argument \"i[0-9]+\" is not a parameter name"); Matcher m = warn.matcher(out); int n = 0; for (int start = 0; m.find(start); start = m.start() + 1) { n++; } if (n != count) error("unexpected number of warnings reported: " + n + "; expected: " + count); Pattern warnCount = Pattern.compile("(?ms).*^([0-9]+) warnings$.*"); m = warnCount.matcher(out); if (m.matches()) { n = Integer.parseInt(m.group(1)); if (n != count) error("unexpected number of warnings reported: " + n + "; expected: " + count); } else error("total count not found"); }
18. MaxWarns#check()
View licensevoid check(String out, int count) { System.err.println(out); Pattern warn = Pattern.compile("warning - @param argument \"i[0-9]+\" is not a parameter name"); Matcher m = warn.matcher(out); int n = 0; for (int start = 0; m.find(start); start = m.start() + 1) { n++; } if (n != count) error("unexpected number of warnings reported: " + n + "; expected: " + count); Pattern warnCount = Pattern.compile("(?ms).*^([0-9]+) warnings$.*"); m = warnCount.matcher(out); if (m.matches()) { n = Integer.parseInt(m.group(1)); if (n != count) error("unexpected number of warnings reported: " + n + "; expected: " + count); } else error("total count not found"); }
19. RegexNameFinderTest#testFindSingleTokenPattern()
View license@Test public void testFindSingleTokenPattern() { Pattern testPattern = Pattern.compile("test"); String sentence[] = new String[] { "a", "test", "b", "c" }; Pattern[] patterns = new Pattern[] { testPattern }; Map<String, Pattern[]> regexMap = new HashMap<>(); String type = "testtype"; regexMap.put(type, patterns); RegexNameFinder finder = new RegexNameFinder(regexMap); Span[] result = finder.find(sentence); assertTrue(result.length == 1); assertTrue(result[0].getStart() == 1); assertTrue(result[0].getEnd() == 2); }
20. RegexNameFinderTest#testFindTokenizdPattern()
View license@Test public void testFindTokenizdPattern() { Pattern testPattern = Pattern.compile("[0-9]+ year"); String sentence[] = new String[] { "a", "80", "year", "b", "c" }; Pattern[] patterns = new Pattern[] { testPattern }; Map<String, Pattern[]> regexMap = new HashMap<>(); String type = "match"; regexMap.put(type, patterns); RegexNameFinder finder = new RegexNameFinder(regexMap); Span[] result = finder.find(sentence); assertTrue(result.length == 1); assertTrue(result[0].getStart() == 1); assertTrue(result[0].getEnd() == 3); assertTrue(result[0].getType().equals("match")); }
21. RegexNameFinderTest#testFindMatchingPatternWithoutMatchingTokenBounds()
View license@Test public void testFindMatchingPatternWithoutMatchingTokenBounds() { // does match "0 year" Pattern testPattern = Pattern.compile("[0-8] year"); String sentence[] = new String[] { "a", "80", "year", "c" }; Pattern[] patterns = new Pattern[] { testPattern }; Map<String, Pattern[]> regexMap = new HashMap<>(); String type = "testtype"; regexMap.put(type, patterns); RegexNameFinder finder = new RegexNameFinder(regexMap); Span[] result = finder.find(sentence); assertTrue(result.length == 0); }
22. OptionableProperties#loadArguments()
View licensepublic void loadArguments(String[] args) { Pattern parameterPattern = Pattern.compile("--(.*?)=(.*?)"); Pattern optionPattern = Pattern.compile("--(.*?)"); for (String arg : args) { Matcher parameterMatcher = parameterPattern.matcher(arg); if (parameterMatcher.matches()) { String parameter = parameterMatcher.group(1); String value = parameterMatcher.group(2); this.setProperty(parameter, value); } else { Matcher optionMatcher = optionPattern.matcher(arg); if (optionMatcher.matches()) { String option = optionMatcher.group(1); this.setProperty(option, "true"); } } } }
23. AternativeApproach#test3()
View license/** * In this test we use a simple Pattern to replace the log instanciation * without influence on Log declaration. * */ public void test3() { Pattern pat = Pattern.compile("LogFactory.getFactory\\(\\).getInstance\\("); String s = "Log log = LogFactory.getFactory().getInstance(\"x\");"; Matcher m = pat.matcher(s); assertTrue(m.find()); String r = m.replaceAll("LoggerFactory.getLogger("); assertEquals("Log log = LoggerFactory.getLogger(\"x\");", r); String nonMatching = "Log log = xxx;"; pat.matcher(nonMatching); assertFalse(m.find()); }
24. AternativeApproach#test5()
View license/** * In this test we combine two Pattern to achieve the intended conversion */ public void test5() { Pattern pat = Pattern.compile("(\\sLog\\b)"); String s = "public Log myLog =LogFactory.getFactory().getInstance(myClass.class);"; Matcher m = pat.matcher(s); assertTrue(m.find()); String r = m.replaceAll(" Logger"); assertEquals("public Logger myLog =LogFactory.getFactory().getInstance(myClass.class);", r); Pattern pat2 = Pattern.compile("LogFactory.getFactory\\(\\).getInstance\\("); m = pat2.matcher(r); assertTrue(m.find()); r = m.replaceAll("LoggerFactory.getLogger("); assertEquals("public Logger myLog =LoggerFactory.getLogger(myClass.class);", r); }
25. PennTreebankTokenizer#split()
View license@Override public String[] split(String text) { for (Pattern regexp : CONTRACTIONS2) text = regexp.matcher(text).replaceAll("$1 $2"); for (Pattern regexp : CONTRACTIONS3) text = regexp.matcher(text).replaceAll("$1 $2 $3"); text = DELIMITERS[0].matcher(text).replaceAll(" $1 "); text = DELIMITERS[1].matcher(text).replaceAll(" $1"); text = DELIMITERS[2].matcher(text).replaceAll(" $1"); text = DELIMITERS[3].matcher(text).replaceAll(" . "); String[] words = WHITESPACE.split(text); if (words.length > 1 && words[words.length - 1].equals(".")) { if (EnglishAbbreviations.contains(words[words.length - 2])) { words[words.length - 2] = words[words.length - 2] + "."; } } return words; }
26. Pattern2Test#testCategory()
View licenseprivate void testCategory(String cat, String... matches) { String pa = "{" + cat + "}"; String pat = "\\p" + pa; String npat = "\\P" + pa; Pattern p = Pattern.compile(pat); Pattern pn = Pattern.compile(npat); for (int j = 0; j < matches.length; j++) { String t = matches[j]; boolean invert = t.startsWith("-"); if (invert) { // test negative case, expected to fail t = t.substring(1); assertFalse("expected '" + t + "' to not be matched " + "by pattern '" + pat, p.matcher(t).matches()); assertTrue("expected '" + t + "' to " + "be matched by pattern '" + npat, pn.matcher(t).matches()); } else { assertTrue("expected '" + t + "' to be matched " + "by pattern '" + pat, p.matcher(t).matches()); assertFalse("expected '" + t + "' to " + "not be matched by pattern '" + npat, pn.matcher(t).matches()); } } }
27. Utils#find()
View license/** * A small implementation of UNIX find. * @param matchRegex Only collect paths that match this regex. * @param pruneRegex Don't recurse down a path that matches this regex. May be null. * @throws IOException if File.getCanonicalPath() fails. */ public static List<File> find(final File startpath, final String matchRegex, final String pruneRegex) throws IOException { final Pattern matchPattern = Pattern.compile(matchRegex, Pattern.CASE_INSENSITIVE); final Pattern prunePattern = pruneRegex == null ? null : Pattern.compile(pruneRegex, Pattern.CASE_INSENSITIVE); final Set<String> visited = new HashSet<String>(); final List<File> found = new ArrayList<File>(); class Search { void search(final File path) throws IOException { if (prunePattern != null && prunePattern.matcher(path.getAbsolutePath()).matches()) return; String cpath = path.getCanonicalPath(); if (!visited.add(cpath)) return; if (matchPattern.matcher(path.getAbsolutePath()).matches()) found.add(path); if (path.isDirectory()) for (File sub : path.listFiles()) search(sub); } } new Search().search(startpath); return found; }
28. MatcherTest#testPosCompositeGroup()
View license@Test public void testPosCompositeGroup() { String[] posExamples = { "aabbcc", "aacc", "bbaabbcc" }; String[] negExamples = { "aabb", "bb", "bbaabb" }; Pattern posPat = Pattern.compile("(aa|bb){1,3}+cc"); Pattern negPat = Pattern.compile("(aa|bb){1,3}+bb"); Matcher mat; for (String element : posExamples) { mat = posPat.matcher(element); assertTrue(mat.matches()); } for (String element : negExamples) { mat = negPat.matcher(element); assertFalse(mat.matches()); } assertTrue(Pattern.matches("(aa|bb){1,3}+bb", "aabbaabb")); }
29. MatcherTest#testPosAltGroup()
View license@Test public void testPosAltGroup() { String[] posExamples = { "aacc", "bbcc", "cc" }; String[] negExamples = { "bb", "aa" }; Pattern posPat = Pattern.compile("(aa|bb)?+cc"); Pattern negPat = Pattern.compile("(aa|bb)?+bb"); Matcher mat; for (String element : posExamples) { mat = posPat.matcher(element); assertTrue(posPat.toString() + " vs: " + element, mat.matches()); } for (String element : negExamples) { mat = negPat.matcher(element); assertFalse(mat.matches()); } assertTrue(Pattern.matches("(aa|bb)?+bb", "aabb")); }
30. ActivityDiagramText#preparse()
View licenseprivate String preparse(String line) { String parsed_line = ""; Pattern p_empty = Pattern.compile("\\s*"); Pattern p_title = Pattern.compile(title_pattern); if (!p_empty.matcher(line).matches()) { Pattern p = Pattern.compile(line_pattern); Matcher m_title = p_title.matcher(line); if (m_title.matches()) { parsed_line = null; title = m_title.group(1); } else if (p.matcher(line).matches()) { parsed_line = line; } else { parsed_line = null; } } return parsed_line; }
31. HTMLDecoder#decode()
View licensepublic static String decode(String html) { com.lincanbin.carbonforum.util.markdown.TextEditor ed = new com.lincanbin.carbonforum.util.markdown.TextEditor(html); Pattern p1 = Pattern.compile("&#(\\d+);"); ed.replaceAll(p1, new com.lincanbin.carbonforum.util.markdown.Replacement() { public String replacement(Matcher m) { String charDecimal = m.group(1); char ch = (char) Integer.parseInt(charDecimal); return Character.toString(ch); } }); Pattern p2 = Pattern.compile("&#x([0-9a-fA-F]+);"); ed.replaceAll(p2, new com.lincanbin.carbonforum.util.markdown.Replacement() { public String replacement(Matcher m) { String charHex = m.group(1); char ch = (char) Integer.parseInt(charHex, 16); return Character.toString(ch); } }); return ed.toString(); }
32. StringUtil#isNumberOrAlpha()
View license/**?????????????? * @param inputed * @return */ public static boolean isNumberOrAlpha(String inputed) { if (inputed == null) { Log.e(TAG, "isNumberOrAlpha inputed == null >> return false;"); return false; } Pattern pNumber = Pattern.compile("[0-9]*"); Matcher mNumber; Pattern pAlpha = Pattern.compile("[a-zA-Z]"); Matcher mAlpha; for (int i = 0; i < inputed.length(); i++) { mNumber = pNumber.matcher(inputed.substring(i, i + 1)); mAlpha = pAlpha.matcher(inputed.substring(i, i + 1)); if (!mNumber.matches() && !mAlpha.matches()) { return false; } } currentString = inputed; return true; }
33. StringUtil#isNumberOrAlpha()
View license/**?????????????? * @param inputed * @return */ public static boolean isNumberOrAlpha(String inputed) { if (inputed == null) { Log.e(TAG, "isNumberOrAlpha inputed == null >> return false;"); return false; } Pattern pNumber = Pattern.compile("[0-9]*"); Matcher mNumber; Pattern pAlpha = Pattern.compile("[a-zA-Z]"); Matcher mAlpha; for (int i = 0; i < inputed.length(); i++) { mNumber = pNumber.matcher(inputed.substring(i, i + 1)); mAlpha = pAlpha.matcher(inputed.substring(i, i + 1)); if (!mNumber.matches() && !mAlpha.matches()) { return false; } } currentString = inputed; return true; }
34. ArquillianPackager#validTestDependency()
View licenseprivate static boolean validTestDependency(MavenCoordinate coordinate) { Pattern[] patterns = new Pattern[] { Pattern.compile("^log4j$"), Pattern.compile("^slf4j-log4j12$"), Pattern.compile("^slf4j-simple") }; boolean valid = true; for (Pattern p : patterns) { if (p.matcher(coordinate.getArtifactId()).matches()) { valid = false; break; } } if (!valid) { debug("Discarded test dependency " + coordinate.toCanonicalForm()); } return valid; }
35. AbstractExternalFilter#getParseSettings()
View license@NotNull protected ParseSettings getParseSettings(@NotNull String url) { Pattern startSection = ourClassDataStartPattern; Pattern endSection = ourClassDataEndPattern; boolean anchorPresent = false; Matcher anchorMatcher = ourAnchorSuffix.matcher(url); if (anchorMatcher.find()) { anchorPresent = true; startSection = Pattern.compile(Pattern.quote("<a name=\"" + anchorMatcher.group(1) + "\""), Pattern.CASE_INSENSITIVE); endSection = ourNonClassDataEndPattern; } return new ParseSettings(startSection, endSection, !anchorPresent, anchorPresent); }
36. PerceptronModel#tagSet()
View license/** Reconstruct that tag set that was used to train the model by decoding some of the features. * This is slow and brittle but should work! Only if "-" is not in the tag set.... */ @Override Set<String> tagSet() { Set<String> tags = Generics.newHashSet(); Pattern p1 = Pattern.compile("Q0TQ1T-([^-]+)-.*"); Pattern p2 = Pattern.compile("S0T-(.*)"); for (String feat : featureWeights.keySet()) { Matcher m1 = p1.matcher(feat); if (m1.matches()) { tags.add(m1.group(1)); } Matcher m2 = p2.matcher(feat); if (m2.matches()) { tags.add(m2.group(1)); } } // Add the end of sentence tag! // The SR model doesn't use it, but other models do and report it. // todo [cdm 2014]: Maybe we should reverse the convention here?!? tags.add(Tagger.EOS_TAG); return tags; }
37. BsonGeneratorTest#patterns()
View license@Test public void patterns() throws Exception { Pattern pattern = Pattern.compile("a.*a", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); Map<String, Object> data = new LinkedHashMap<String, Object>(); data.put("pattern", pattern); BSONObject obj = generateAndParse(data); Pattern result = (Pattern) obj.get("pattern"); assertNotNull(result); assertEquals(pattern.pattern(), result.pattern()); assertEquals(pattern.flags(), result.flags()); }
38. BsonParserTest#parseComplex()
View license@Test public void parseComplex() throws Exception { BSONObject o = new BasicBSONObject(); o.put("Timestamp", new BSONTimestamp(0xAABB, 0xCCDD)); o.put("Symbol", new Symbol("Test")); o.put("ObjectId", new org.bson.types.ObjectId(Integer.MAX_VALUE, -2, Integer.MIN_VALUE)); Pattern p = Pattern.compile(".*", Pattern.CASE_INSENSITIVE | Pattern.DOTALL | Pattern.MULTILINE | Pattern.UNICODE_CASE); o.put("Regex", p); Map<?, ?> data = parseBsonObject(o); assertEquals(new Timestamp(0xAABB, 0xCCDD), data.get("Timestamp")); assertEquals(new de.undercouch.bson4jackson.types.Symbol("Test"), data.get("Symbol")); ObjectId oid = (ObjectId) data.get("ObjectId"); assertEquals(Integer.MAX_VALUE, oid.getTime()); assertEquals(-2, oid.getMachine()); assertEquals(Integer.MIN_VALUE, oid.getInc()); Pattern p2 = (Pattern) data.get("Regex"); assertEquals(p.flags(), p2.flags()); assertEquals(p.pattern(), p2.pattern()); }
39. MoreStringsTest#testRegexPatternForAny()
View license@Test public void testRegexPatternForAny() { Pattern varArgTestPattern = Pattern.compile(MoreStrings.regexPatternForAny("foo", "bar")); assertTrue(varArgTestPattern.matcher("bar").matches()); assertTrue(varArgTestPattern.matcher("foo").matches()); assertFalse(varArgTestPattern.matcher("mehfoo").matches()); Pattern iterabeArgTestPattern = Pattern.compile(".*" + MoreStrings.regexPatternForAny(ImmutableSet.of("raz", "meh")) + "$"); assertTrue(iterabeArgTestPattern.matcher("hello raz").matches()); assertTrue(iterabeArgTestPattern.matcher("hello meh").matches()); assertFalse(iterabeArgTestPattern.matcher("hello meh hi").matches()); }
40. HeaderMatcherTest#simpleMatches()
View license@Test public void simpleMatches() throws Exception { Pattern hatPattern = Pattern.compile("(.*)hat(.*)"); Pattern headPattern = Pattern.compile("head...."); StringReader reader = new StringReader("The mad hatter"); matcher.read(reader); assertTrue(matcher.matches(hatPattern)); assertFalse(matcher.matches(headPattern)); reader = new StringReader("headache"); matcher.read(reader); assertFalse(matcher.matches(hatPattern)); assertTrue(matcher.matches(headPattern)); }
41. SubstringNodeTest#testGetRegexpWithLdapFilterSpecialChars()
View license/** * Tests StringTools.getRegex() with some LDAP filter special characters. */ @Test public void testGetRegexpWithLdapFilterSpecialChars() throws Exception { Pattern[] patterns = new Pattern[] { SubstringNode.getRegex(null, new String[] { "(" }, null), SubstringNode.getRegex(null, new String[] { ")" }, null), SubstringNode.getRegex(null, new String[] { "*" }, null), SubstringNode.getRegex(null, new String[] { "\\" }, null) }; for (Pattern pattern : patterns) { boolean b1 = pattern.matcher("a(b*c\\d)e").matches(); assertTrue(b1); boolean b3 = pattern.matcher("Test test").matches(); assertFalse(b3); } }
42. ServerParser#getKeyValueMap()
View licenseprotected Map getKeyValueMap(FileReader fileReader) throws IOException { String LIGTTTPD_PATTERN = "^\\s*(server|dir-listing)\\.(port|document-root|errorlog|activate)\\s*=\\s*([^#;]*)"; String NGINX_PATTERN = "^\\s*(listen|server_name|root)\\s([^#;]*)"; BufferedReader reader = new BufferedReader(fileReader); Pattern lighttpdPattern = Pattern.compile(LIGTTTPD_PATTERN); Pattern nginxPattern = Pattern.compile(NGINX_PATTERN); String line; Matcher matcher; while ((line = reader.readLine()) != null) { matcher = lighttpdPattern.matcher(line); if (matcher.find()) { keyValue.put(matcher.group(2), matcher.group(3).replaceAll("\"", "").trim()); } matcher = nginxPattern.matcher(line); if (matcher.find()) { keyValue.put(matcher.group(1), matcher.group(2).replaceAll("\"", "").trim()); } } return keyValue; }
43. MaxWarns#check()
View licensevoid check(String out, int count) { System.err.println(out); Pattern warn = Pattern.compile("warning - @param argument \"i[0-9]+\" is not a parameter name"); Matcher m = warn.matcher(out); int n = 0; for (int start = 0; m.find(start); start = m.start() + 1) { n++; } if (n != count) error("unexpected number of warnings reported: " + n + "; expected: " + count); Pattern warnCount = Pattern.compile("(?ms).*^([0-9]+) warnings$.*"); m = warnCount.matcher(out); if (m.matches()) { n = Integer.parseInt(m.group(1)); if (n != count) error("unexpected number of warnings reported: " + n + "; expected: " + count); } else error("total count not found"); }
44. GoVersion#matcherFor()
View licenseprivate Matcher matcherFor(String version) { Pattern updateServerPattern = Pattern.compile("^(?:(\\d+)\\.)?(?:(\\d+)\\.)?(?:(\\d+)\\-)?(?:(\\d+))$"); Pattern serverVersionPattern = Pattern.compile("^(?:(\\d+)\\.)?(?:(\\d+)\\.)?(?:(\\d+)\\s*\\()?(?:(\\d+)\\-)?(?:(\\w+)\\))$"); Matcher matcher = null; matcher = updateServerPattern.matcher(version); if (matcher.matches()) return matcher; matcher = serverVersionPattern.matcher(version); if (matcher.matches()) return matcher; return null; }
45. EmailSanitizer#cleanEmail()
View licenseprivate static String cleanEmail(String email) throws UnsupportedEncodingException { if (email == null) { return null; } // Fix any incorrect dashes Matcher dashes = DASHES_PATTERN.matcher(email); email = dashes.replaceAll("-"); // Some emails may contain HTML encoded characters, so decode just in case email = URLDecoder.decode(email, "UTF-8"); email = email.toLowerCase().trim(); for (Pattern p : EMAIL_STRIP_PATTERNS) { Matcher matcher = p.matcher(email); email = matcher.replaceAll(""); } for (Pattern r : AT_SYMBOL_REPLACEMENTS) { Matcher matcher = r.matcher(email); email = matcher.replaceAll("@"); } return email; }
46. Utilities#cleanBody()
View license/** * Cleaninig of the body of text prior to term extraction. Try to remove the * pdf extraction garbage and the citation marks. */ public static String cleanBody(String text) { if (text == null) return null; String res = ""; // clean pdf weird output for math. glyphs Pattern cleaner = Pattern.compile("[-]?[a-z][\\d]+[ ]*"); // System.out.println("RegEx Syntax error! There is something wrong with my pattern" // + rs); Matcher m = cleaner.matcher(text); res = m.replaceAll(""); Pattern cleaner2 = Pattern.compile("[\\w]*[@|#|=]+[\\w]+"); // System.out.println("RegEx Syntax error! There is something wrong with my pattern" // + rs); Matcher m2 = cleaner2.matcher(res); res = m2.replaceAll(""); res = res.replace("Introduction", ""); return res; }
47. Extended14TypesTest#testRegexPattern()
View licensepublic void testRegexPattern() { // setup Pattern pattern = Pattern.compile("^[ae]*$", Pattern.MULTILINE | Pattern.UNIX_LINES); String expectedXml = "" + "<java.util.regex.Pattern>\n" + " <pattern>^[ae]*$</pattern>\n" + " <flags>9</flags>\n" + "</java.util.regex.Pattern>"; // execute String actualXml = xstream.toXML(pattern); Pattern result = (Pattern) xstream.fromXML(actualXml); // verify assertEquals(expectedXml, actualXml); assertEquals(pattern.pattern(), result.pattern()); assertEquals(pattern.flags(), result.flags()); assertFalse("regex should not hava matched", result.matcher("oooo").matches()); assertTrue("regex should have matched", result.matcher("aeae").matches()); }
48. GitLocalChangesWouldBeOverwrittenDetector#onLineAvailable()
View license@Override public void onLineAvailable(@NotNull String line, @NotNull Key outputType) { super.onLineAvailable(line, outputType); for (Pattern pattern : myOperation.getPatterns()) { Matcher m = pattern.matcher(line); if (m.matches()) { myMessageDetected = true; myAffectedFiles.add(m.group(1)); break; } } }
49. Sentence#create()
View licensepublic static Sentence create(String param) { Pattern pattern = Pattern.compile("(\\[(([^\\s]+/[0-9a-zA-Z]+)\\s+)+?([^\\s]+/[0-9a-zA-Z]+)]/[0-9a-zA-Z]+)|([^\\s]+/[0-9a-zA-Z]+)"); Matcher matcher = pattern.matcher(param); List<IWord> wordList = new LinkedList<IWord>(); while (matcher.find()) { String single = matcher.group(); IWord word = WordFactory.create(single); if (word == null) { logger.warning("??" + single + "???????"); return null; } wordList.add(word); } return new Sentence(wordList); }
50. AntDomPattern#acceptPath()
View licensepublic boolean acceptPath(final String relativePath) { final String path = relativePath.replace('\\', '/'); boolean accepted = myIncludePatterns.size() == 0; for (Pattern includePattern : myIncludePatterns) { if (includePattern.matcher(path).matches()) { accepted = true; break; } } if (accepted) { for (Pattern excludePattern : myExcludePatterns) { if (excludePattern.matcher(path).matches()) { accepted = false; break; } } } return accepted; }
51. ExternalChangesDetectionVcsTest#testGeneration()
View license@Test public void testGeneration() throws Exception { for (int i = 0; i < 100; i++) { final File f = new File(myClientRoot, "f" + i + ".txt"); f.createNewFile(); } myWorkingCopyDir.refresh(false, true); myChangeListManager.ensureUpToDate(false); final List<VirtualFile> unversionedFiles = ((ChangeListManagerImpl) myChangeListManager).getUnversionedFiles(); final Pattern pattern = Pattern.compile("f([0-9])+\\.txt"); int cnt = 0; for (VirtualFile unversionedFile : unversionedFiles) { if (VfsUtil.isAncestor(myWorkingCopyDir, unversionedFile, true)) { ++cnt; Assert.assertTrue(pattern.matcher(unversionedFile.getName()).matches()); } } Assert.assertEquals(100, cnt); }
52. VersionUtil#parseVersion()
View license@Nullable public static Version parseVersion(@NotNull String version, @NotNull Pattern... patterns) { String[] versions = null; for (Pattern pattern : patterns) { Matcher matcher = pattern.matcher(version); if (matcher.find()) { String versionGroup = matcher.group(1); if (versionGroup != null) { versions = versionGroup.split("\\."); break; } } } if (versions == null || versions.length < 2) { return null; } return new Version(Integer.parseInt(versions[0]), Integer.parseInt(versions[1]), (versions.length > 2) ? Integer.parseInt(versions[2]) : 0); }
53. StringUtil#formatLinks()
View license@NotNull @Contract(pure = true) public static String formatLinks(@NotNull String message) { Pattern linkPattern = Pattern.compile("http://[a-zA-Z0-9\\./\\-\\+]+"); StringBuffer result = new StringBuffer(); Matcher m = linkPattern.matcher(message); while (m.find()) { m.appendReplacement(result, "<a href=\"" + m.group() + "\">" + m.group() + "</a>"); } m.appendTail(result); return result.toString(); }
54. UsefulTestCase#filteredSuite()
View license@NotNull public static Test filteredSuite(@RegExp String regexp, @NotNull Test test) { final Pattern pattern = Pattern.compile(regexp); final TestSuite testSuite = new TestSuite(); new Processor<Test>() { @Override public boolean process(Test test) { if (test instanceof TestSuite) { for (int i = 0, len = ((TestSuite) test).testCount(); i < len; i++) { process(((TestSuite) test).testAt(i)); } } else if (pattern.matcher(test.toString()).find()) { testSuite.addTest(test); } return false; } }.process(test); return testSuite; }
55. FileTypesTest#testMaskToPattern()
View licensepublic void testMaskToPattern() { for (char i = 0; i < 256; i++) { if (i == '?' || i == '*') continue; String str = "x" + i + "y"; assertTrue("char: " + i + "(" + (int) i + ")", PatternUtil.fromMask(str).matcher(str).matches()); } String allSymbols = "+.\\*/^?$[]()"; assertTrue(PatternUtil.fromMask(allSymbols).matcher(allSymbols).matches()); Pattern pattern = PatternUtil.fromMask("?\\?/*"); assertTrue(pattern.matcher("a\\b/xyz").matches()); assertFalse(pattern.matcher("x/a\\b").matches()); }
56. AbstractEditorTest#setupFolding()
View license/** * Setups {@link Editor#getFoldingModel() folding model} of the {@link #getEditor() current editor} according to the given text * that is expected to contain information obtained from the {@link FoldingModelImpl#toString()}. * * @param data string representation of the target fold regions */ protected static void setupFolding(@NotNull String data) { Scanner scanner = new Scanner(data); Pattern pattern = Pattern.compile("FoldRegion ([+-])\\((\\d+):(\\d+)"); final List<Trinity<Boolean, Integer, Integer>> infos = new ArrayList<>(); while (scanner.findInLine(pattern) != null) { final MatchResult match = scanner.match(); boolean expanded = "-".equals(match.group(1)); int startOffset = Integer.parseInt(match.group(2)); int endOffset = Integer.parseInt(match.group(3)); infos.add(new Trinity<>(expanded, startOffset, endOffset)); } final FoldingModel foldingModel = myEditor.getFoldingModel(); foldingModel.runBatchFoldingOperation(() -> { for (Trinity<Boolean, Integer, Integer> info : infos) { final FoldRegion region = foldingModel.addFoldRegion(info.second, info.third, "..."); assert region != null; region.setExpanded(info.first); } }); }
57. AbstractEditorTest#setupDocument()
View license/** * Setups document of the {@link #getEditor() current editor} according to the given text that is expected to contain * information about document lines obtained from the {@link DocumentImpl#dumpState()}. * * @param data string representation of the target document's lines */ @SuppressWarnings("UnusedDeclaration") protected static void setupDocument(@NotNull String data) { Scanner scanner = new Scanner(data); Pattern pattern = Pattern.compile("(\\d+)\\s*:\\s*(\\d+)\\s*-\\s*(\\d+)"); StringBuilder buffer = new StringBuilder(); while (scanner.findInLine(pattern) != null) { final MatchResult match = scanner.match(); int startOffset = Integer.parseInt(match.group(2)); int endOffset = Integer.parseInt(match.group(3)); buffer.append(StringUtil.repeatSymbol('a', endOffset - startOffset)).append('\n'); } if (buffer.length() > 0) { buffer.setLength(buffer.length() - 1); } myEditor.getDocument().setText(buffer.toString()); }
58. VMOptionsTest#testRegExpr()
View license@Test public void testRegExpr() { Pattern p = VMOptions.MemoryKind.HEAP.pattern; Matcher m = p.matcher("-option -Xmx128mb -option"); assertTrue(m.find()); assertEquals("128", m.group(1)); assertEquals("mb", m.group(2)); m = p.matcher("-option -Xmx -option"); assertTrue(m.find()); assertEquals("", m.group(1)); assertEquals("", m.group(2)); m = p.matcher("-option -Xxx -option"); assertFalse(m.find()); }
59. SaveProjectAsTemplateAction#getEncodedContent()
View licenseprivate static String getEncodedContent(VirtualFile virtualFile, Project project, Map<String, String> parameters, String fileHeaderTemplateName, boolean shouldEscape) throws IOException { String text = VfsUtilCore.loadText(virtualFile); final FileTemplate template = FileTemplateManager.getInstance(project).getDefaultTemplate(fileHeaderTemplateName); final String templateText = template.getText(); final Pattern pattern = FileTemplateUtil.getTemplatePattern(template, project, new TIntObjectHashMap<String>()); String result = convertTemplates(text, pattern, templateText, shouldEscape); result = ProjectTemplateFileProcessor.encodeFile(result, virtualFile, project); for (Map.Entry<String, String> entry : parameters.entrySet()) { result = result.replace(entry.getKey(), "${" + entry.getValue() + "}"); } return result; }
60. ChooseByNamePopup#getTransformedPattern()
View licensepublic static String getTransformedPattern(String pattern, ChooseByNameModel model) { Pattern regex = null; if (StringUtil.containsAnyChar(pattern, ":,;@[(") || pattern.contains(" line ")) { // quick test if reg exp should be used regex = patternToDetectLinesAndColumns; } if (model instanceof GotoClassModel2) { if (pattern.indexOf('#') != -1) { regex = patternToDetectMembers; } if (pattern.indexOf('$') != -1) { regex = patternToDetectAnonymousClasses; } } if (regex != null) { final Matcher matcher = regex.matcher(pattern); if (matcher.matches()) { pattern = matcher.group(1); } } return pattern; }
61. FindModel#compileRegExp()
View licensepublic Pattern compileRegExp() { String toFind = getStringToFind(); Pattern pattern = myPattern; if (pattern == PatternUtil.NOTHING) { try { myPattern = pattern = Pattern.compile(toFind, isCaseSensitive() ? Pattern.MULTILINE : Pattern.MULTILINE | Pattern.CASE_INSENSITIVE); } catch (PatternSyntaxException e) { myPattern = pattern = null; } } return pattern; }
62. StringPattern#matches()
View license@NotNull public StringPattern matches(@NonNls @NotNull final String s) { final String escaped = StringUtil.escapeToRegexp(s); if (escaped.equals(s)) { return equalTo(s); } // may throw PatternSyntaxException here final Pattern pattern = Pattern.compile(s); return with(new ValuePatternCondition<String>("matches") { @Override public boolean accepts(@NotNull final String str, final ProcessingContext context) { return pattern.matcher(newBombedCharSequence(str)).matches(); } @Override public Collection<String> getValues() { return Collections.singleton(s); } }); }
63. LightQuickFixTestCase#parseActionHint()
View license@NotNull public static Pair<String, Boolean> parseActionHint(@NotNull PsiFile file, @NotNull String contents, @NotNull @NonNls @RegExp String actionPattern) { PsiFile hostFile = InjectedLanguageManager.getInstance(file.getProject()).getTopLevelFile(file); final Commenter commenter = LanguageCommenters.INSTANCE.forLanguage(hostFile.getLanguage()); String comment = commenter.getLineCommentPrefix(); if (comment == null) { comment = commenter.getBlockCommentPrefix(); } // "quick fix action text to perform" "should be available" assert comment != null : commenter; Pattern pattern = Pattern.compile("^" + comment.replace("*", "\\*") + actionPattern, Pattern.DOTALL); Matcher matcher = pattern.matcher(contents); assertTrue("No comment found in " + file.getVirtualFile(), matcher.matches()); final String text = matcher.group(1); final Boolean actionShouldBeAvailable = Boolean.valueOf(matcher.group(2)); return Pair.create(text, actionShouldBeAvailable); }
64. JavaTestFinder#collectTests()
View licenseprivate boolean collectTests(PsiClass klass, Processor<Pair<? extends PsiNamedElement, Integer>> processor) { GlobalSearchScope scope = getSearchScope(klass, false); PsiShortNamesCache cache = PsiShortNamesCache.getInstance(klass.getProject()); String klassName = klass.getName(); Pattern pattern = Pattern.compile(".*" + StringUtil.escapeToRegexp(klassName) + ".*", Pattern.CASE_INSENSITIVE); HashSet<String> names = new HashSet<String>(); cache.getAllClassNames(names); for (String eachName : names) { if (pattern.matcher(eachName).matches()) { for (PsiClass eachClass : cache.getClassesByName(eachName, scope)) { if (isTestClass(eachClass, klass)) { if (!processor.process(Pair.create(eachClass, TestFinderHelper.calcTestNameProximity(klassName, eachName)))) { return true; } } } } } return false; }
65. FileHeaderChecker#checkFileHeader()
View licensestatic ProblemDescriptor checkFileHeader(@NotNull PsiFile file, @NotNull InspectionManager manager, boolean onTheFly) { TIntObjectHashMap<String> offsetToProperty = new TIntObjectHashMap<String>(); FileTemplate defaultTemplate = FileTemplateManager.getInstance(file.getProject()).getDefaultTemplate(FileTemplateManager.FILE_HEADER_TEMPLATE_NAME); Pattern pattern = FileTemplateUtil.getTemplatePattern(defaultTemplate, file.getProject(), offsetToProperty); Matcher matcher = pattern.matcher(file.getViewProvider().getContents()); if (!matcher.matches()) { return null; } PsiComment element = PsiTreeUtil.findElementOfClassAtRange(file, matcher.start(1), matcher.end(1), PsiComment.class); if (element == null) { return null; } LocalQuickFix[] fixes = createQuickFix(matcher, offsetToProperty, file.getProject(), onTheFly); String description = InspectionsBundle.message("default.file.template.description"); return manager.createProblemDescriptor(element, description, onTheFly, fixes, ProblemHighlightType.GENERIC_ERROR_OR_WARNING); }
66. DidYouMeanSuggestor#replaceSuggestion()
View licenseprivate String replaceSuggestion(String queryString, String term, String suggestedTerm) { Pattern pattern = Pattern.compile("\\b(" + term + ")\\b(?!\\:)", Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(queryString); StringBuffer sb = new StringBuffer(); if (matcher.find()) { matcher.appendReplacement(sb, suggestedTerm); matcher.appendTail(sb); if (matcher.find()) { return null; } } else { return queryString; } return sb.toString(); }
67. RegexpMetricsFilter#matches()
View license@Override public boolean matches(String name, Metric metric) { if (filterPatterns.isEmpty()) { return true; } for (Pattern eachPattern : filterPatterns) { if (eachPattern.matcher(name).find()) { return true; } } return false; }
68. HexStringConverter#decodeHex()
View licensepublic String decodeHex(String hexString) { Pattern p = Pattern.compile("(0x([a-fA-F0-9]{2}([a-fA-F0-9]{2})?))"); Matcher m = p.matcher(hexString); StringBuffer buf = new StringBuffer(); int hashCode = 0; while (m.find()) { hashCode = Integer.decode("0x" + m.group(2)); m.appendReplacement(buf, new String(Character.toChars(hashCode))); } m.appendTail(buf); return buf.toString(); }
69. DataTransform#processColumnNames()
View license/** * Method to construct a mapping between column names and their * corresponding column IDs. The mapping is used to prepare the * specification file in <code>processSpecFile()</code>. * * @param fs * @param prop * @param headerLine * @param smallestFile * @return * @throws IllegalArgumentException * @throws IOException */ private static HashMap<String, Integer> processColumnNames(FileSystem fs, CSVFileFormatProperties prop, String headerLine, String smallestFile) throws IllegalArgumentException, IOException { HashMap<String, Integer> colNames = new HashMap<String, Integer>(); String escapedDelim = Pattern.quote(prop.getDelim()); Pattern compiledDelim = Pattern.compile(escapedDelim); String[] names = compiledDelim.split(headerLine, -1); for (int i = 0; i < names.length; i++) colNames.put(UtilFunctions.unquote(names[i].trim()), i + 1); return colNames; }
70. RegexUtils#getTwoMatchedGroups()
View licensepublic static Pair<String, String> getTwoMatchedGroups(String line, String regEx) { Pattern pattern = Pattern.compile(regEx); Matcher matcher = pattern.matcher(line); Pair<String, String> match = null; while (matcher.find()) { Pair<String, String> pair = new ImmutablePair<String, String>(matcher.group(0), matcher.group(1)); match = pair; } return match; }
71. RegexUtils#getMatches()
View licensepublic static List<String> getMatches(String line, String regEx, int group) { Pattern pattern = Pattern.compile(regEx); Matcher matcher = pattern.matcher(line); List<String> matches = new ArrayList<String>(); while (matcher.find()) { matches.add(matcher.group(group)); } return matches; }
72. SimpleSemanticAnalyzer#parseFunction()
View licenseprivate void parseFunction(String cmd, String regex) throws HiveAuthzPluginException { Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(cmd); if (matcher.find()) { String udfClass = matcher.group(matcher.groupCount()); if (udfClass.contains("'")) { currentTb = udfClass.split("'")[1]; } else { currentTb = udfClass; } } else { throw new HiveAuthzPluginException("this command " + cmd + " is not match create function grammar"); } }
73. SimpleSemanticAnalyzer#parseShowIndex()
View licenseprivate void parseShowIndex(String cmd, String regex) throws HiveAuthzPluginException { Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(cmd); if (matcher.find()) { String dbName = matcher.group(matcher.groupCount()); String tbName = matcher.group(3); if (dbName != null) { currentDb = dbName; currentTb = tbName; } else { extractDbAndTb(tbName); } } else { throw new HiveAuthzPluginException("this command " + cmd + " is not match show index grammar"); } }
74. DeNormalize#capitalizeLineFirstLetter()
View license/** * Capitalize the first letter of a line. This should be the last denormalization step applied to * a line. * * @param line The single-line input string * @return The input string modified as described above */ public static String capitalizeLineFirstLetter(String line) { String result = null; Pattern regexp = Pattern.compile("[^\\p{Punct}\\p{Space}¡¿]"); Matcher matcher = regexp.matcher(line); if (matcher.find()) { String match = matcher.group(0); result = line.replaceFirst(match, match.toUpperCase()); } else { result = line; } return result; }
75. FileUtil#isIgnoredFile()
View licenseprivate static boolean isIgnoredFile(File f, String srcBaseDirPath, Collection<Pattern> ignoredFilePathPatterns) throws IOException { if (ignoredFilePathPatterns.isEmpty()) { return false; } srcBaseDirPath = ensureEndsWithFileSeparator(srcBaseDirPath); String filePath = f.getAbsolutePath(); if (!filePath.startsWith(srcBaseDirPath)) { throw new IOException("Unexpected: " + StringUtil.jQuote(filePath) + " doesn't start with " + StringUtil.jQuote(srcBaseDirPath)); } String slashRelFilePath = pathToUnixStyle(filePath.substring(srcBaseDirPath.length() - 1)); for (Pattern pattern : ignoredFilePathPatterns) { if (pattern.matcher(slashRelFilePath).matches()) { return true; } } return false; }
76. RegexpHelper#getPattern()
View licensestatic Pattern getPattern(String patternString, int flags) throws TemplateModelException { PatternCacheKey patternKey = new PatternCacheKey(patternString, flags); Pattern result; synchronized (patternCache) { result = (Pattern) patternCache.get(patternKey); } if (result != null) { return result; } try { result = Pattern.compile(patternString, flags); } catch (PatternSyntaxException e) { throw new _TemplateModelException(e, "Malformed regular expression: ", new _DelayedGetMessage(e)); } synchronized (patternCache) { patternCache.put(patternKey, result); } return result; }
77. DataValidatorBuilder#validatePhoneNumber()
View licensepublic DataValidatorBuilder validatePhoneNumber() { if (this.value == null && this.ignoreNullValue) { return this; } boolean validationErr = true; /* * supports numbers, parentheses(), hyphens and may contain + sign in * the beginning and can contain whitespaces in between and length * allowed is 0-25 chars. */ final String regex = "^\\+?[0-9. ()-]{0,25}$"; final Pattern pattern = Pattern.compile(regex); final Matcher matcher = pattern.matcher(this.value.toString()); if (matcher.matches()) { validationErr = false; } if (validationErr) { final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource).append(".").append(this.parameter).append(".format.is.invalid"); final StringBuilder defaultEnglishMessage = new StringBuilder("The ").append(this.resource).append(this.parameter).append(" is in invalid format, should contain '-','+','()' and numbers only."); final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), defaultEnglishMessage.toString(), this.parameter, this.value); this.dataValidationErrors.add(error); } return this; }
78. HDFSResourceResolver#matchAttribute()
View licensepublic List<FileStatus> matchAttribute(List<FileStatus> statuses, String target) { List<FileStatus> result = new ArrayList<>(); Pattern pattern = Pattern.compile("^" + target); for (FileStatus status : statuses) { String path = status.getPath().toUri().getPath(); if (pattern.matcher(path).find()) { result.add(status); } } if (result.size() == 0) { return statuses; } return result; }
79. PatternUtils#matchString()
View licensepublic static String matchString(String dwr, String regex) { if (dwr == null) { return null; } // Pattern mPattern = Pattern.compile(regex); Matcher m = mPattern.matcher(dwr); if (m.find()) { return m.group(); } else { return ""; } }
80. ProductResultInfoRetriever#retrieveSupplementalInfo()
View license@Override void retrieveSupplementalInfo() throws IOException { String encodedProductID = URLEncoder.encode(productID, "UTF-8"); String uri = "http://www.google." + LocaleManager.getProductSearchCountryTLD(context) + "/m/products?ie=utf8&oe=utf8&scoring=p&source=zxing&q=" + encodedProductID; CharSequence content = HttpHelper.downloadViaHttp(uri, HttpHelper.ContentType.HTML); for (Pattern p : PRODUCT_NAME_PRICE_PATTERNS) { Matcher matcher = p.matcher(content); if (matcher.find()) { append(productID, source, new String[] { unescapeHTML(matcher.group(1)), unescapeHTML(matcher.group(2)) }, uri); break; } } }
81. TestMakeTranslateName#testMakeDictionary()
View licensepublic void testMakeDictionary() throws Exception { Set<String> wordSet = new TreeSet<String>(); Pattern pattern = Pattern.compile("^[a-zA-Z]+ *(\\[.*?])? *([\\u4E00-\\u9FA5]+) ?[:??]"); int found = 0; for (String line : IOUtil.readLineList("D:\\Doc\\???\\??????.txt")) { Matcher matcher = pattern.matcher(line); if (matcher.find()) { wordSet.add(matcher.group(2)); ++found; } } System.out.println("????" + found + "?"); IOUtil.saveCollectionToTxt(wordSet, "data/dictionary/person/??????.txt"); }
82. TestMakeTranslateName#testRegex()
View licensepublic void testRegex() throws Exception { Pattern pattern = Pattern.compile("^[a-zA-Z]+ (\\[.*?])? ?([\\u4E00-\\u9FA5]+) ?[:??]"); String text = "Adey ???Adam?????????? \n" + "Adkin ???:Adarn??????????? \n" + "Adkins ????:???????Adkin,??“?????”(son of Adkin)??????? \n" + "Adlam [??????] ??????????????????“???+?????”(noble?protection?helmet) \n" + "Zena [???] ?????????????“??”(woman)? \n" + "Zenas [???] ??????????????“?????????”(gift of Zeus?the chief Greek god)? \n" + "Zenia [???]????Xeniq???? \n" + "Zenobia [???] ???????????????“??????+??”(the chief Greek god Zeus+life)? \n" + "Zillah [???] ??????????????“?”(shade)? \n" + "Zoe [???]?????????????“??”?life?? \n" + "Zouch [??????] ???Such???? "; Matcher matcher = pattern.matcher(text); if (matcher.find()) { System.out.println(matcher.group(2)); } }
83. TestSentence#testCreate()
View licensepublic void testCreate() throws Exception { String text = "???/nz 1?1?/t ?/ng ?/p ?/w [??/nsf ??/n]/nz ?/w ??/v ?/w"; Pattern pattern = Pattern.compile("(\\[(.+/[a-z]+)]/[a-z]+)|([^\\s]+/[a-z]+)"); Matcher matcher = pattern.matcher(text); while (matcher.find()) { String param = matcher.group(); assertEquals(param, WordFactory.create(param).toString()); } assertEquals(text, Sentence.create(text).toString()); }
84. TestXianDaiHanYu#testMakeDictionary()
View licensepublic void testMakeDictionary() throws Exception { String text = IOUtil.readTxt("D:\\Doc\\???\\?????????????_??.txt").toLowerCase(); Pattern pattern = Pattern.compile("?([\\u4E00-\\u9FA5]+)?([abcdefghijklmnopqrstuwxyz?á?à?é?è?í?ì?ó?ò?ú?ù?????•’?]+)"); Matcher matcher = pattern.matcher(text); StringDictionary dictionary = new StringDictionary(); while (matcher.find()) { String word = matcher.group(1); String pinyinString = matcher.group(2); List<Pinyin> pinyinList = TonePinyinString2PinyinConverter.convert(pinyinString, false); if (pinyinList.size() != word.length() || hasNull(pinyinList)) { System.out.println("???? " + word + " " + pinyinString + " " + pinyinList); continue; } dictionary.add(word, convertList2String(pinyinList)); } System.out.println(dictionary.size()); dictionary.save("data/dictionary/pinyin/pinyin.xd.txt"); }
85. Inflector#replaceAllWithUppercase()
View license/** * Utility method to replace all occurrences given by the specific backreference with its uppercased form, and remove all * other backreferences. * * The Java {@link Pattern regular expression processing} does not use the preprocessing directives <code>\l</code>, * <code>\u</code>, <code>\L</code>, and <code>\U</code>. If so, such directives could be used in the replacement string * to uppercase or lowercase the backreferences. For example, <code>\L1</code> would lowercase the first backreference, and * <code>\u3</code> would uppercase the 3rd backreference. * * * @param input * @param regex * @param groupNumberToUppercase * @return the input string with the appropriate characters converted to upper-case */ protected static String replaceAllWithUppercase(String input, String regex, int groupNumberToUppercase) { Pattern underscoreAndDotPattern = Pattern.compile(regex); Matcher matcher = underscoreAndDotPattern.matcher(input); StringBuffer sb = new StringBuffer(); while (matcher.find()) { matcher.appendReplacement(sb, matcher.group(groupNumberToUppercase).toUpperCase()); } matcher.appendTail(sb); return sb.toString(); }
86. Inflector#replaceAllWithUppercase()
View license/** * Utility method to replace all occurrences given by the specific backreference with its uppercased form, and remove all * other backreferences. * * The Java {@link Pattern regular expression processing} does not use the preprocessing directives <code>\l</code>, * <code>\u</code>, <code>\L</code>, and <code>\U</code>. If so, such directives could be used in the replacement string * to uppercase or lowercase the backreferences. For example, <code>\L1</code> would lowercase the first backreference, and * <code>\u3</code> would uppercase the 3rd backreference. * * * @param input * @param regex * @param groupNumberToUppercase * @return the input string with the appropriate characters converted to upper-case */ protected static String replaceAllWithUppercase(String input, String regex, int groupNumberToUppercase) { Pattern underscoreAndDotPattern = Pattern.compile(regex); Matcher matcher = underscoreAndDotPattern.matcher(input); StringBuffer sb = new StringBuffer(); while (matcher.find()) { matcher.appendReplacement(sb, matcher.group(groupNumberToUppercase).toUpperCase()); } matcher.appendTail(sb); return sb.toString(); }
87. LWFTAdaptor#parseArgs()
View license@Override public String parseArgs(String params) { conf = control.getConfiguration(); MAX_READ_SIZE = conf.getInt(MAX_READ_SIZE_OPT, DEFAULT_MAX_READ_SIZE); Pattern cmd = Pattern.compile("(\\d+)\\s+(.+)\\s?"); Matcher m = cmd.matcher(params); if (m.matches()) { //check for first-byte offset. If absent, assume we just got a path. offsetOfFirstByte = Long.parseLong(m.group(1)); toWatch = new File(m.group(2)); } else { toWatch = new File(params.trim()); } return toWatch.getAbsolutePath(); }
88. RCheckFTAdaptor#parseArgs()
View license/** * Check for date-modified and offset; if absent assume we just got a name. */ @Override public String parseArgs(String params) { Pattern cmd = Pattern.compile("d:(\\d+)\\s+(\\d+)\\s+(.+)\\s?"); Matcher m = cmd.matcher(params); if (m.matches()) { prevFileLastModDate = Long.parseLong(m.group(1)); offsetOfFirstByte = Long.parseLong(m.group(2)); toWatch = new File(m.group(3)).getAbsoluteFile(); } else { toWatch = new File(params.trim()).getAbsoluteFile(); } fBaseName = toWatch.getName(); return toWatch.getAbsolutePath(); }
89. JobHistoryLog#extractCounters()
View licenseprotected void extractCounters(ChukwaRecord record, String input) { String regex = "[^\\(]*\\)\\([0-9]+"; Pattern p = Pattern.compile(regex); log.debug("counter contents: " + input); Matcher matcher = p.matcher(input); while (matcher.find()) { String tmp = matcher.group(); String[] items = tmp.split("\\)\\("); record.add(items[0], items[1]); log.debug("data schema: " + items[0] + " data fields: " + items[1]); } }
90. StringUtils#ghFlavoredMarkdown()
View licensepublic static String ghFlavoredMarkdown(String input) { final StringBuffer output = new StringBuffer(); final Pattern usernamePattern = Pattern.compile("@([A-Za-z0-9]?[A-Za-z0-9-]+)"); final Matcher usernameMatcher = usernamePattern.matcher(input); /* Loop through @username matches */ while (usernameMatcher.find()) { /* Grab the username from the match (without the '@') */ final String username = usernameMatcher.group(1); /* Create a URL to the user's profile */ final String r = "<a href=\"https://github.com/" + username + "\">@" + username + "</a>"; /* Append the replacement */ usernameMatcher.appendReplacement(output, r); } /* Append the rest of the non-matching text */ usernameMatcher.appendTail(output); return output.toString(); }
91. Computer#relocateOldLogs()
View license/*package*/ static void relocateOldLogs(File dir) { final Pattern logfile = Pattern.compile("slave-(.*)\\.log(\\.[0-9]+)?"); File[] logfiles = dir.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return logfile.matcher(name).matches(); } }); if (logfiles == null) return; for (File f : logfiles) { Matcher m = logfile.matcher(f.getName()); if (m.matches()) { File newLocation = new File(dir, "logs/slaves/" + m.group(1) + "/slave.log" + Util.fixNull(m.group(2))); newLocation.getParentFile().mkdirs(); boolean relocationSuccessfull = f.renameTo(newLocation); if (relocationSuccessfull) { // The operation will fail if mkdir fails LOGGER.log(Level.INFO, "Relocated log file {0} to {1}", new Object[] { f.getPath(), newLocation.getPath() }); } else { LOGGER.log(Level.WARNING, "Cannot relocate log file {0} to {1}", new Object[] { f.getPath(), newLocation.getPath() }); } } else { assert false; } } }
92. ComputerLauncher#checkJavaVersion()
View license/** * Given the output of "java -version" in <code>r</code>, determine if this * version of Java is supported, or throw {@link IOException}. * * @param logger * where to log the output * @param javaCommand * the command executed, used for logging * @param r * the output of "java -version" */ protected static void checkJavaVersion(final PrintStream logger, String javaCommand, final BufferedReader r) throws IOException { String line; Pattern p = Pattern.compile("(?i)(?:java|openjdk) version \"([0-9.]+).*\""); while (null != (line = r.readLine())) { Matcher m = p.matcher(line); if (m.matches()) { final String versionStr = m.group(1); logger.println(Messages.ComputerLauncher_JavaVersionResult(javaCommand, versionStr)); try { if (new DeweyDecimal(versionStr).isLessThan(new DeweyDecimal("1.6"))) { throw new IOException(Messages.ComputerLauncher_NoJavaFound(line)); } } catch (NumberFormatException x) { throw new IOException(Messages.ComputerLauncher_NoJavaFound(line)); } return; } } logger.println(Messages.ComputerLauncher_UknownJavaVersion(javaCommand)); throw new IOException(Messages.ComputerLauncher_UknownJavaVersion(javaCommand)); }
93. TestPatternGenerator#testAcceptStrings()
View license@Test public void testAcceptStrings() { String[] input = new String[3]; input[0] = "foo"; input[1] = "bar"; input[2] = "baz"; String regex = PatternGenerator.acceptStrings(input); Pattern pattern = Pattern.compile(regex); assertTrue(pattern.matcher("foo").matches()); assertTrue(pattern.matcher("bar").matches()); assertTrue(pattern.matcher("baz").matches()); assertFalse(pattern.matcher("foobaz").matches()); assertFalse(pattern.matcher("").matches()); }
94. TestPatternGenerator#testSubsequence()
View license@Test public void testSubsequence() { String[] input = new String[3]; input[0] = "foo"; input[1] = "bar"; input[2] = "baz"; String regex = PatternGenerator.acceptStrings(input); Pattern pattern = Pattern.compile(regex); assertTrue(pattern.matcher("foo").find()); assertTrue(pattern.matcher("bar").find()); assertTrue(pattern.matcher("baz").find()); assertTrue(pattern.matcher("hellofoo").find()); assertTrue(pattern.matcher("hellofooworld").find()); assertFalse(pattern.matcher("").find()); }
95. MAFParser#breakQuotedString()
View licenseprivate String[] breakQuotedString(String subjectString) { List<String> matchList = new ArrayList<String>(); Pattern regex = Pattern.compile("[^\\s\"']+|\"([^\"]*)\"|'([^']*)'"); Matcher regexMatcher = regex.matcher(subjectString); while (regexMatcher.find()) { if (regexMatcher.group(1) != null) { // Add double-quoted string without the quotes matchList.add(regexMatcher.group(1)); } else if (regexMatcher.group(2) != null) { // Add single-quoted string without the quotes matchList.add(regexMatcher.group(2)); } else { // Add unquoted word matchList.add(regexMatcher.group()); } } return matchList.toArray(new String[] {}); }
96. SearchHelper#findOpeningTag()
View license@Nullable private static TextRange findOpeningTag(@NotNull CharSequence sequence, int position, @NotNull String tagName) { final String tagBeginning = "<" + tagName; final Pattern pattern = Pattern.compile(Pattern.quote(tagBeginning), Pattern.CASE_INSENSITIVE); final Matcher matcher = pattern.matcher(sequence.subSequence(0, position)); final List<Integer> possibleBeginnings = Lists.newArrayList(); while (matcher.find()) { possibleBeginnings.add(matcher.start()); } final List<Integer> reversedBeginnings = Lists.reverse(possibleBeginnings); for (int openingTagPos : reversedBeginnings) { final int openingTagEndPos = openingTagPos + tagBeginning.length(); final int closeBracketPos = StringUtil.indexOf(sequence, '>', openingTagEndPos); if (closeBracketPos > 0 && (closeBracketPos == openingTagEndPos || sequence.charAt(openingTagEndPos) == ' ')) { return new TextRange(openingTagPos, closeBracketPos); } } return null; }
97. ProjectService#getLocationFromStackLine()
View licenseprotected ApexCodeLocation getLocationFromStackLine(String name, String stackTrace) { if (Utils.isEmpty(name) || Utils.isEmpty(stackTrace)) { logger.warn("Unable to get location from stacktrace - name and/or stacktrace is null"); return null; } final Pattern pattern = Pattern.compile(".*line ([0-9]+?), column ([0-9]+?).*", Pattern.DOTALL | Pattern.MULTILINE | Pattern.CASE_INSENSITIVE); final Matcher matcher = pattern.matcher(stackTrace); matcher.find(); String line = matcher.group(1); String column = matcher.group(2); return new ApexCodeLocation(name, line, column); }
98. RegExpTest#testRegExp()
View license/** * @throws Exception If failed. */ public void testRegExp() throws Exception { String normal = "swap-spaces/space1/b53b3a3d6ab90ce0268229151c9bde11|b53b3a3d6ab90ce0268229151c9bde11|1315392441288"; byte[] b1 = new byte[200]; byte[] b2 = normal.getBytes(); U.arrayCopy(b2, 0, b1, 30, b2.length); CharSequence corrupt = new String(b1); String ptrn = "[a-z0-9/\\-]+\\|[a-f0-9]+\\|[0-9]+"; Pattern p = Pattern.compile(ptrn); Matcher matcher = p.matcher(corrupt); assert matcher.find(); X.println(String.valueOf(matcher.start())); assert normal.matches(ptrn); }
99. PAssertTest#testContainsInAnyOrderFalse()
View license/** * Tests that {@code containsInAnyOrder} fails when and how it should. */ @Test @Category(RunnableOnService.class) public void testContainsInAnyOrderFalse() throws Exception { Pipeline pipeline = TestPipeline.create(); PCollection<Integer> pcollection = pipeline.apply(Create.of(1, 2, 3, 4)); PAssert.that(pcollection).containsInAnyOrder(2, 1, 4, 3, 7); Throwable exc = runExpectingAssertionFailure(pipeline); Pattern expectedPattern = Pattern.compile("Expected: iterable over \\[((<4>|<7>|<3>|<2>|<1>)(, )?){5}\\] in any order"); // A loose pattern, but should get the job done. assertTrue("Expected error message from PAssert with substring matching " + expectedPattern + " but the message was \"" + exc.getMessage() + "\"", expectedPattern.matcher(exc.getMessage()).find()); }
100. DisplayDataTest#testAnonymousClassNamespace()
View license@Test public void testAnonymousClassNamespace() { DisplayData data = DisplayData.from(new HasDisplayData() { @Override public void populateDisplayData(DisplayData.Builder builder) { builder.add(DisplayData.item("foo", "bar")); } }); DisplayData.Item<?> item = (DisplayData.Item<?>) data.items().toArray()[0]; final Pattern anonClassRegex = Pattern.compile(Pattern.quote(DisplayDataTest.class.getName()) + "\\$\\d+$"); assertThat(item.getNamespace(), new CustomTypeSafeMatcher<String>("anonymous class regex: " + anonClassRegex) { @Override protected boolean matchesSafely(String item) { java.util.regex.Matcher m = anonClassRegex.matcher(item); return m.matches(); } }); }