java.util.regex.Pattern

Here are the examples of the java api class java.util.regex.Pattern taken from open source projects.

1. GroupCounts#testPatternCompileGroupCount()

Project: checker-framework
Source File: GroupCounts.java
View license
void 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()

Project: log-synth
Source File: SchemaSamplerTest.java
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()

Project: svgtoandroid
Source File: StdColorUtil.java
View license
public 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()

Project: buck
Source File: JavacErrorParser.java
View license
public 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()

Project: ode
Source File: HierarchicalProperties.java
View license
private 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. HTMLDecoder#decode()

View license
public 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();
}

7. StringUtil#isNumberOrAlpha()

Project: Android-ZBLibrary
Source File: StringUtil.java
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;
}

8. StringUtil#isNumberOrAlpha()

Project: Android-ZBLibrary
Source File: StringUtil.java
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;
}

9. BsonGeneratorTest#patterns()

Project: bson4jackson
Source File: BsonGeneratorTest.java
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());
}

10. BsonParserTest#parseComplex()

Project: bson4jackson
Source File: BsonParserTest.java
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());
}

11. MoreStringsTest#testRegexPatternForAny()

Project: buck
Source File: MoreStringsTest.java
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());
}

12. ArquillianPackager#validTestDependency()

Project: camel
Source File: ArquillianPackager.java
View license
private 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;
}

13. AbstractExternalFilter#getParseSettings()

Project: consulo
Source File: AbstractExternalFilter.java
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);
}

14. PerceptronModel#tagSet()

Project: CoreNLP
Source File: PerceptronModel.java
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;
}

15. HeaderMatcherTest#simpleMatches()

Project: creadur-rat
Source File: HeaderMatcherTest.java
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));
}

16. 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);
    }
}

17. ServerParser#getKeyValueMap()

Project: DroidPHP
Source File: ServerParser.java
View license
protected 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;
}

18. MaxWarns#check()

Project: error-prone-javac
Source File: MaxWarns.java
View license
void 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. GoVersion#matcherFor()

Project: gocd
Source File: GoVersion.java
View license
private 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;
}

20. EmailSanitizer#cleanEmail()

Project: grobid
Source File: EmailSanitizer.java
View license
private 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;
}

21. Utilities#cleanBody()

Project: grobid
Source File: Utilities.java
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;
}

22. MotifFinderSource#getMatcher()

Project: igv
Source File: MotifFinderSource.java
View license
/**
     * See [email protected] #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);
}

23. FilterPattern#methodMatches()

View license
public 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();
}

24. 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);
}

25. MavenUtil#isIncluded()

Project: intellij-community
Source File: MavenUtil.java
View license
public 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;
}

26. Pattern2Test#testCategory()

Project: j2objc
Source File: Pattern2Test.java
View license
private 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()

Project: jdk7u-jdk
Source File: Utils.java
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. FormattedSqlChangeLogParser#parseSqlCheckCondition()

View license
private 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 + "'.");
}

29. SimpleTaggerWithConstraints#getCRF()

View license
public 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;
}

30. HTMLDecoder#decode()

Project: markdownj
Source File: HTMLDecoder.java
View license
public 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();
}

31. 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);
}

32. AcknowledgeMessage#parsePayLoad()

Project: openhab
Source File: AcknowledgeMessage.java
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;
    }
}

33. Verifier#verifyUncommonTrapFired()

Project: openjdk
Source File: Verifier.java
View license
private 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));
}

34. MaxWarns#check()

Project: openjdk
Source File: MaxWarns.java
View license
void 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");
}

35. MaxWarns#check()

Project: openjdk
Source File: MaxWarns.java
View license
void 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");
}

36. RegexNameFinderTest#testFindSingleTokenPattern()

Project: opennlp
Source File: RegexNameFinderTest.java
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);
}

37. RegexNameFinderTest#testFindTokenizdPattern()

Project: opennlp
Source File: RegexNameFinderTest.java
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"));
}

38. RegexNameFinderTest#testFindMatchingPatternWithoutMatchingTokenBounds()

Project: opennlp
Source File: RegexNameFinderTest.java
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);
}

39. IntrospectorDumperClassPoolVisitor#filter()

View license
public 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;
}

40. OptionableProperties#loadArguments()

View license
public 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");
            }
        }
    }
}

41. AternativeApproach#test3()

Project: slf4j
Source File: AternativeApproach.java
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());
}

42. AternativeApproach#test5()

Project: slf4j
Source File: AternativeApproach.java
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);
}

43. PennTreebankTokenizer#split()

Project: smile
Source File: PennTreebankTokenizer.java
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;
}

44. MatcherTest#testPosCompositeGroup()

Project: teavm
Source File: MatcherTest.java
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"));
}

45. MatcherTest#testPosAltGroup()

Project: teavm
Source File: MatcherTest.java
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"));
}

46. ActivityDiagramText#preparse()

Project: umlet
Source File: ActivityDiagramText.java
View license
private 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;
}

47. Extended14TypesTest#testRegexPattern()

Project: xstream
Source File: Extended14TypesTest.java
View license
public 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. ConfigData#parseAuthUser()

View license
/**
   * Parses the authUser property value.
   *
   * @return The owner email of the project
   * @throws Exception
   */
private String parseAuthUser() throws Exception {
    String authUser = getString(AUTH_USER);
    if (authUser == null || authUser.isEmpty()) {
        throw new Exception("You must set " + AUTH_USER + " property.");
    }
    Pattern pattern = Pattern.compile(EMAIL_PATTERN);
    if (pattern.matcher(authUser).find()) {
        return authUser;
    } else {
        throw new Exception("Invalid value in " + AUTH_USER + " property");
    }
}

49. ConfigData#parseServiceAccountEmail()

View license
/**
   * Parses the serviceAccountEmail property value.
   *
   * @return The email generated for the service account credentials
   * @throws Exception
   */
private String parseServiceAccountEmail() throws Exception {
    String serviceAccountEmail = getString(SERVICE_ACCOUNT_EMAIL);
    if (serviceAccountEmail == null) {
        throw new Exception("You must set " + SERVICE_ACCOUNT_EMAIL + " property.");
    }
    Pattern pattern = Pattern.compile(EMAIL_PATTERN);
    if (pattern.matcher(serviceAccountEmail).find()) {
        return serviceAccountEmail;
    } else {
        throw new Exception("Invalid value in " + SERVICE_ACCOUNT_EMAIL + " property");
    }
}

50. ConfigData#parseDomain()

View license
/**
   * Parses the domain property value.
   *
   * @return Domain
   * @throws Exception
   */
private String parseDomain() throws Exception {
    String domain = getString(DOMAIN);
    if (domain == null || appName.isEmpty()) {
        throw new Exception("You must set " + DOMAIN + " property.");
    }
    Pattern pattern = Pattern.compile(DOMAIN_PATTERN);
    if (pattern.matcher(domain).find()) {
        return domain;
    } else {
        throw new Exception("Invalid value in " + DOMAIN + " property");
    }
}

51. TypedQueryValidator#validateCorrectTableName()

Project: Achilles
Source File: TypedQueryValidator.java
View license
public static void validateCorrectTableName(String queryString, AbstractEntityProperty<?> meta) {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(format("Validate that the query string %s is related to the entity meta %s", queryString));
    }
    String tableName = meta.getTableOrViewName().toLowerCase();
    final Pattern pattern = Pattern.compile(".* from " + OPTIONAL_KEYSPACE_PREFIX + tableName + "(?: )?.*");
    validateTrue(pattern.matcher(queryString).matches(), "The typed query [%s] should contain the table name '%s' if the entity type is '%s'", queryString, tableName, meta.entityClass.getCanonicalName());
}

52. RenditionPatternPicker#getRendition()

View license
/**
     * Gets the rendition which matches against the constructor's Regex pattern.
     * <p>
     * If no matches are made and an Original exists, returns the Original.
     * <p>
     * If no matches are made and an Original doesn't exist, return the first Rendition.
     *
     * @param asset Asset whose Renditions will be selected.
     * @return The first rendition whose name matches the supplied pattern (via constructor).
     */
@Override
public final Rendition getRendition(final Asset asset) {
    final List<Rendition> renditions = asset.getRenditions();
    final Pattern p = getPattern();
    boolean hasOriginal = asset.getOriginal() != null;
    boolean hasRenditions = renditions.size() > 0;
    for (final Rendition rendition : renditions) {
        final Matcher m = p.matcher(rendition.getName());
        if (m.find()) {
            return rendition;
        }
    }
    if (hasOriginal) {
        return asset.getOriginal();
    } else if (hasRenditions) {
        return renditions.get(0);
    } else {
        return null;
    }
}

53. CookieUtil#getCookies()

Project: acs-aem-commons
Source File: CookieUtil.java
View license
/**
     * Gets Cookies from the Request whose names match the provides Regex
     *
     * @param request Request to get the Cookie from
     * @param regex   Regex to match against Cookie names
     * @return Cookies which match the Regex
     */
public static List<Cookie> getCookies(final HttpServletRequest request, final String regex) {
    final ArrayList<Cookie> foundCookies = new ArrayList<Cookie>();
    if (StringUtils.isBlank(regex)) {
        return foundCookies;
    }
    final Cookie[] cookies = request.getCookies();
    if (cookies == null) {
        return Collections.emptyList();
    }
    final Pattern p = Pattern.compile(regex);
    for (final Cookie cookie : cookies) {
        final Matcher m = p.matcher(cookie.getName());
        if (m.matches()) {
            foundCookies.add(cookie);
        }
    }
    return foundCookies;
}

54. RainbowSpanActivity#highlight()

View license
private void highlight(String query) {
    String text = textView.getText().toString();
    SpannableString spannableString = new SpannableString(text);
    Pattern pattern = Pattern.compile(query.toLowerCase());
    Matcher matcher = pattern.matcher(text.toLowerCase());
    while (matcher.find()) {
        spannableString.setSpan(new StyleSpan(Typeface.BOLD), matcher.start(), matcher.end(), 0);
        spannableString.setSpan(new RainbowSpan(this), matcher.start(), matcher.end(), 0);
    }
    textView.setText(spannableString);
}

55. NameValidator#validate()

Project: airavata
Source File: NameValidator.java
View license
/**
     * @param name
     * @return Is it valid name?
     */
public static boolean validate(String name) {
    // Set the name pattern string
    Pattern p = Pattern.compile("([a-zA-Z]){1,}([0-9]|_|\\.|[a-zA-Z]){0,}$");
    // Match the given string with the pattern
    Matcher m = p.matcher(name);
    // Check whether match is found
    boolean matchFound = m.matches();
    return matchFound;
}

56. StringUtil#getURLS()

Project: airavata
Source File: StringUtil.java
View license
// Merits for the following function should go to 
// http://blog.houen.net/java-get-url-from-string/ 
public static List<String> getURLS(String text) {
    List<String> links = new ArrayList<String>();
    String regex = "\\(?\\b((http|https|ftp)://|www[.])[-A-Za-z0-9+&@#/%?=~_()|!:,.;]*[-A-Za-z0-9+&@#/%=~_()|]";
    Pattern p = Pattern.compile(regex);
    Matcher m = p.matcher(text);
    while (m.find()) {
        String urlStr = m.group();
        if (urlStr.startsWith("(") && urlStr.endsWith(")")) {
            urlStr = urlStr.substring(1, urlStr.length() - 1);
        }
        if (!links.contains(urlStr)) {
            links.add(urlStr);
        }
    }
    return links;
}

57. LSFOutputParser#parseJobId()

Project: airavata
Source File: LSFOutputParser.java
View license
@Override
public String parseJobId(String jobName, String rawOutput) throws SSHApiException {
    String regJobId = "jobId";
    // regex - look ahead and match
    Pattern pattern = Pattern.compile("(?=(?<" + regJobId + ">\\d+)\\s+\\w+\\s+" + jobName + ")");
    if (rawOutput != null) {
        Matcher matcher = pattern.matcher(rawOutput);
        if (matcher.find()) {
            return matcher.group(regJobId);
        } else {
            logger.error("No match is found for JobName");
            return null;
        }
    } else {
        logger.error("Error: RawOutput shouldn't be null");
        return null;
    }
}

58. PBSOutputParser#parseJobId()

Project: airavata
Source File: PBSOutputParser.java
View license
@Override
public String parseJobId(String jobName, String rawOutput) throws SSHApiException {
    /* output will look like
        Job Id: 2080802.gordon-fe2.local
            Job_Name = A312402627
        */
    String regJobId = "jobId";
    Pattern pattern = Pattern.compile("(?<" + regJobId + ">[^\\s]*)\\s*.* " + jobName);
    if (rawOutput != null) {
        Matcher matcher = pattern.matcher(rawOutput);
        if (matcher.find()) {
            return matcher.group(regJobId);
        } else {
            log.error("No match is found for JobName");
            return null;
        }
    } else {
        log.error("Error: RawOutput shouldn't be null");
        return null;
    }
}

59. SlurmOutputParser#parseJobId()

Project: airavata
Source File: SlurmOutputParser.java
View license
@Override
public String parseJobId(String jobName, String rawOutput) throws SSHApiException {
    String regJobId = "jobId";
    if (jobName == null) {
        return null;
    } else if (jobName.length() > JOB_NAME_OUTPUT_LENGTH) {
        jobName = jobName.substring(0, JOB_NAME_OUTPUT_LENGTH);
    }
    // regex - look ahead and match
    Pattern pattern = Pattern.compile("(?=(?<" + regJobId + ">\\d+)\\s+\\w+\\s+" + jobName + ")");
    if (rawOutput != null) {
        Matcher matcher = pattern.matcher(rawOutput);
        if (matcher.find()) {
            return matcher.group(regJobId);
        } else {
            log.error("No match is found for JobName");
            return null;
        }
    } else {
        log.error("Error: RawOutput shouldn't be null");
        return null;
    }
}

60. UGEOutputParser#parseJobId()

Project: airavata
Source File: UGEOutputParser.java
View license
@Override
public String parseJobId(String jobName, String rawOutput) throws SSHApiException {
    if (jobName.length() > 10) {
        jobName = jobName.substring(0, 10);
    }
    Pattern pattern = Pattern.compile("(?<" + JOB_ID + ">\\S+)\\s+\\S+\\s+(" + jobName + ")");
    Matcher matcher = pattern.matcher(rawOutput);
    if (matcher.find()) {
        return matcher.group(JOB_ID);
    }
    return null;
}

61. UGEEmailParser#parseEmail()

Project: airavata
Source File: UGEEmailParser.java
View license
@Override
public JobStatusResult parseEmail(Message message) throws MessagingException, AiravataException {
    JobStatusResult jobStatusResult = new JobStatusResult();
    String subject = message.getSubject();
    Pattern pattern = Pattern.compile(REGEX);
    Matcher matcher = pattern.matcher(subject);
    try {
        if (matcher.find()) {
            jobStatusResult.setJobId(matcher.group(JOBID));
            jobStatusResult.setJobName(matcher.group(JOBNAME));
            String content = (String) message.getContent();
            jobStatusResult.setState(getJobState(matcher.group(STATUS), content));
        } else {
            log.error("[EJM]: No matched found for subject => \n" + subject);
        }
    } catch (IOException e) {
        throw new AiravataException("[EJM]: Error while reading content of the email message");
    }
    return jobStatusResult;
}

62. AlertManager#parse()

Project: alertsystem
Source File: AlertManager.java
View license
public List<String> parse(String msg) {
    List<String> list = new ArrayList<String>();
    // ??????
    Pattern pattern = Pattern.compile("\\?(.*?)\\?");
    Matcher matcher = pattern.matcher(msg);
    while (matcher.find()) {
        list.add(matcher.group(1));
    }
    // ????[]
    if (list.size() < 4) {
        list.clear();
        pattern = Pattern.compile("\\[(.*?)\\]");
        matcher = pattern.matcher(msg);
        while (matcher.find()) {
            list.add(matcher.group(1));
        }
    }
    // ????4,??ParseError
    if (list.size() < 4)
        return null;
    else
        return list;
}

63. AmbroseHiveFinishHook#getLastCmd()

Project: ambrose
Source File: AmbroseHiveFinishHook.java
View license
private String getLastCmd() {
    CliSessionState cliss = (CliSessionState) SessionState.get();
    Scanner scanner = null;
    try {
        scanner = new Scanner(new File(cliss.fileName));
    } catch (FileNotFoundException e) {
        LOG.error("Can't find Hive script", e);
    }
    if (scanner == null) {
        return null;
    }
    Pattern delim = Pattern.compile(";");
    scanner.useDelimiter(delim);
    String lastLine = null;
    while (scanner.hasNext()) {
        String line = StringUtils.trim(scanner.next().replaceAll("\\n", ""));
        if (line.length() != 0 && !line.startsWith("--")) {
            lastLine = line;
        }
    }
    return lastLine;
}

64. MarkdownProcessor#stripLinkDefinitions()

View license
private void stripLinkDefinitions(com.lincanbin.carbonforum.util.markdown.TextEditor text) {
    Pattern p = Pattern.compile(// ID = $1
    "^[ ]{0,3}\\[(.+)\\]:" + // Space
    "[ \\t]*\\n?[ \\t]*" + // URL = $2
    "<?(\\S+?)>?" + // Space
    "[ \\t]*\\n?[ \\t]*" + // Optional title = $3
    "(?:[\"(](.+?)[\")][ \\t]*)?" + "(?:\\n+|\\Z)", Pattern.MULTILINE);
    text.replaceAll(p, new com.lincanbin.carbonforum.util.markdown.Replacement() {

        public String replacement(Matcher m) {
            String id = m.group(1).toLowerCase();
            String url = encodeAmpsAndAngles(new com.lincanbin.carbonforum.util.markdown.TextEditor(m.group(2))).toString();
            String title = m.group(3);
            if (title == null) {
                title = "";
            }
            title = replaceAll(title, "\"", """);
            linkDefinitions.put(id, new LinkDefinition(url, title));
            return "";
        }
    });
}

65. MarkdownProcessor#doAutoLinks()

View license
private com.lincanbin.carbonforum.util.markdown.TextEditor doAutoLinks(com.lincanbin.carbonforum.util.markdown.TextEditor markup) {
    markup.replaceAll("<((https?|ftp):[^'\">\\s]+)>", "<a href=\"$1\">$1</a>");
    Pattern email = Pattern.compile("<([-.\\w]+\\@[-a-z0-9]+(\\.[-a-z0-9]+)*\\.[a-z]+)>");
    markup.replaceAll(email, new com.lincanbin.carbonforum.util.markdown.Replacement() {

        public String replacement(Matcher m) {
            String address = m.group(1);
            com.lincanbin.carbonforum.util.markdown.TextEditor ed = new com.lincanbin.carbonforum.util.markdown.TextEditor(address);
            unEscapeSpecialChars(ed);
            String addr = encodeEmail(ed.toString());
            String url = encodeEmail("mailto:" + ed.toString());
            return "<a href=\"" + url + "\">" + addr + "</a>";
        }
    });
    return markup;
}

66. MarkdownProcessor#doHeaders()

View license
private TextEditor doHeaders(TextEditor markup) {
    // setext-style headers
    markup.replaceAll("^(.*)\n====+$", "<h1>$1</h1>");
    markup.replaceAll("^(.*)\n----+$", "<h2>$1</h2>");
    // atx-style headers - e.g., "#### heading 4 ####"
    Pattern p = Pattern.compile("^(#{1,6})\\s*(.*?)\\s*\\1?$", Pattern.MULTILINE);
    markup.replaceAll(p, new Replacement() {

        public String replacement(Matcher m) {
            String marker = m.group(1);
            String heading = m.group(2);
            int level = marker.length();
            String tag = "h" + level;
            return "<" + tag + ">" + heading + "</" + tag + ">\n";
        }
    });
    return markup;
}

67. BitMapFragment#getImgSrcList()

View license
/**
     * ??????????
     */
public static List<String> getImgSrcList(String htmlStr) {
    List<String> pics = new ArrayList<String>();
    // ??????
    String regEx_img = "<img.*?src=\"http://(.*?).jpg\"";
    Pattern p_image = Pattern.compile(regEx_img, Pattern.CASE_INSENSITIVE);
    Matcher m_image = p_image.matcher(htmlStr);
    while (m_image.find()) {
        String src = m_image.group(1);
        if (src.length() < 100) {
            pics.add("http://" + src + ".jpg");
        }
    }
    return pics;
}

68. StringUtils#getHrefInnerHtml()

View license
/**
     * get innerHtml from href
     * 
     * <pre>
     * getHrefInnerHtml(null)                                  = ""
     * getHrefInnerHtml("")                                    = ""
     * getHrefInnerHtml("mp3")                                 = "mp3";
     * getHrefInnerHtml("<a innerHtml</a>")                    = "<a innerHtml</a>";
     * getHrefInnerHtml("<a>innerHtml</a>")                    = "innerHtml";
     * getHrefInnerHtml("<a<a>innerHtml</a>")                    = "innerHtml";
     * getHrefInnerHtml("<a href="baidu.com">innerHtml</a>")               = "innerHtml";
     * getHrefInnerHtml("<a href="baidu.com" title="baidu">innerHtml</a>") = "innerHtml";
     * getHrefInnerHtml("   <a>innerHtml</a>  ")                           = "innerHtml";
     * getHrefInnerHtml("<a>innerHtml</a></a>")                      = "innerHtml";
     * getHrefInnerHtml("jack<a>innerHtml</a></a>")                  = "innerHtml";
     * getHrefInnerHtml("<a>innerHtml1</a><a>innerHtml2</a>")        = "innerHtml2";
     * </pre>
     * 
     * @param href
     * @return <ul>
     *         <li>if href is null, return ""</li>
     *         <li>if not match regx, return source</li>
     *         <li>return the last string that match regx</li>
     *         </ul>
     */
public static String getHrefInnerHtml(String href) {
    if (isEmpty(href)) {
        return "";
    }
    String hrefReg = ".*<[\\s]*a[\\s]*.*>(.+?)<[\\s]*/a[\\s]*>.*";
    Pattern hrefPattern = Pattern.compile(hrefReg, Pattern.CASE_INSENSITIVE);
    Matcher hrefMatcher = hrefPattern.matcher(href);
    if (hrefMatcher.matches()) {
        return hrefMatcher.group(1);
    }
    return href;
}

69. StringUtils#getHrefInnerHtml()

View license
/**
     * get innerHtml from href
     * 
     * <pre>
     * getHrefInnerHtml(null)                                  = ""
     * getHrefInnerHtml("")                                    = ""
     * getHrefInnerHtml("mp3")                                 = "mp3";
     * getHrefInnerHtml("<a innerHtml</a>")                    = "<a innerHtml</a>";
     * getHrefInnerHtml("<a>innerHtml</a>")                    = "innerHtml";
     * getHrefInnerHtml("<a<a>innerHtml</a>")                    = "innerHtml";
     * getHrefInnerHtml("<a href="baidu.com">innerHtml</a>")               = "innerHtml";
     * getHrefInnerHtml("<a href="baidu.com" title="baidu">innerHtml</a>") = "innerHtml";
     * getHrefInnerHtml("   <a>innerHtml</a>  ")                           = "innerHtml";
     * getHrefInnerHtml("<a>innerHtml</a></a>")                      = "innerHtml";
     * getHrefInnerHtml("jack<a>innerHtml</a></a>")                  = "innerHtml";
     * getHrefInnerHtml("<a>innerHtml1</a><a>innerHtml2</a>")        = "innerHtml2";
     * </pre>
     * 
     * @param href
     * @return <ul>
     *         <li>if href is null, return ""</li>
     *         <li>if not match regx, return source</li>
     *         <li>return the last string that match regx</li>
     *         </ul>
     */
public static String getHrefInnerHtml(String href) {
    if (isEmpty(href)) {
        return "";
    }
    String hrefReg = ".*<[\\s]*a[\\s]*.*>(.+?)<[\\s]*/a[\\s]*>.*";
    Pattern hrefPattern = Pattern.compile(hrefReg, Pattern.CASE_INSENSITIVE);
    Matcher hrefMatcher = hrefPattern.matcher(href);
    if (hrefMatcher.matches()) {
        return hrefMatcher.group(1);
    }
    return href;
}

70. LinkBuilder#addLinkToSpan()

View license
/**
     * Find the link within the spannable text
     *
     * @param s    spannable text that we are adding the rule to.
     * @param link rule to add to the text.
     */
private void addLinkToSpan(Spannable s, Link link) {
    // get the current text
    Pattern pattern = Pattern.compile(Pattern.quote(link.getText()));
    Matcher matcher = pattern.matcher(text);
    // find one or more links inside the text
    while (matcher.find()) {
        // find the start and end point of the linked text within the TextView
        int start = matcher.start();
        //int start = text.indexOf(link.getText());
        if (start >= 0) {
            int end = start + link.getText().length();
            // add link to the spannable text
            applyLink(link, new Range(start, end), s);
        }
    }
}

71. Utils#isValidEmail()

Project: android-utils
Source File: Utils.java
View license
/**
     * Checks if the input parameter is a valid email.
     **/
public static boolean isValidEmail(String email) {
    final String emailPattern = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
    Matcher matcher;
    Pattern pattern = Pattern.compile(emailPattern);
    matcher = pattern.matcher(email);
    if (matcher != null)
        return matcher.matches();
    else
        return false;
}

72. UrlIntentController#handleIMDb()

View license
private void handleIMDb(String path) {
    final Pattern pattern = Pattern.compile("^http://imdb\\.com/title/(tt\\d{7})$", Pattern.MULTILINE);
    final Matcher matcher = pattern.matcher(path);
    if (matcher.find()) {
        final String imdbIdRequested = matcher.group(1);
        final ProgressDialog dialog = ProgressDialog.show(mActivity, "Loading Movies", null, true);
        mVideoManager.getMovies(new DataResponse<ArrayList<Movie>>() {

            public void run() {
                dialog.dismiss();
                processImdbResults(imdbIdRequested, value);
            }

            ;
        }, mActivity.getApplicationContext());
    } else {
        //TODO: Externalize string
        Toast.makeText(mActivity, "Error parsing IMDb link", Toast.LENGTH_LONG).show();
        mActivity.finish();
    }
}

73. StringUtil#isEmail()

Project: Android-ZBLibrary
Source File: StringUtil.java
View license
//??email??????
public static boolean isEmail(String email) {
    if (isNotEmpty(email, true) == false) {
        return false;
    }
    String str = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
    Pattern p = Pattern.compile(str);
    currentString = email;
    return p.matcher(email).matches();
}

74. StringUtil#isNumer()

Project: Android-ZBLibrary
Source File: StringUtil.java
View license
//????????
public static boolean isNumer(String number) {
    if (isNotEmpty(number, true) == false) {
        return false;
    }
    Pattern pattern = Pattern.compile("[0-9]*");
    Matcher isNum = pattern.matcher(number);
    if (!isNum.matches()) {
        return false;
    }
    currentString = number;
    return true;
}

75. StringUtil#isEmail()

Project: Android-ZBLibrary
Source File: StringUtil.java
View license
//??email??????
public static boolean isEmail(String email) {
    if (isNotEmpty(email, true) == false) {
        return false;
    }
    String str = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
    Pattern p = Pattern.compile(str);
    currentString = email;
    return p.matcher(email).matches();
}

76. StringUtil#isNumer()

Project: Android-ZBLibrary
Source File: StringUtil.java
View license
//????????
public static boolean isNumer(String number) {
    if (isNotEmpty(number, true) == false) {
        return false;
    }
    Pattern pattern = Pattern.compile("[0-9]*");
    Matcher isNum = pattern.matcher(number);
    if (!isNum.matches()) {
        return false;
    }
    currentString = number;
    return true;
}

77. string#replaceValues()

Project: AndroidQuickUtils
Source File: string.java
View license
public static String replaceValues(final String template, final Map<String, String> values) {
    final StringBuffer sb = new StringBuffer();
    final Pattern pattern = Pattern.compile("\\$\\{(.*?)\\}", Pattern.DOTALL);
    final Matcher matcher = pattern.matcher(template);
    while (matcher.find()) {
        final String key = matcher.group(1);
        final String replacement = values.get(key);
        if (replacement == null) {
            throw new IllegalArgumentException("Template contains unmapped key: " + key);
        }
        matcher.appendReplacement(sb, replacement);
    }
    matcher.appendTail(sb);
    return sb.toString();
}

78. DateField#fromString()

Project: androrm
Source File: DateField.java
View license
/**
	 * Constructs a [email protected] Date} object from the given string. <br />
	 * The String must be in the format: YYYY-MM-DDTHH:MM:SS.
	 * 
	 * @param date	String representing the date.
	 */
public void fromString(String date) {
    Pattern pattern = Pattern.compile("(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})");
    if (date != null) {
        Matcher matcher = pattern.matcher(date);
        if (matcher.matches()) {
            int year = Integer.valueOf(matcher.group(1));
            int month = Integer.valueOf(matcher.group(2)) - 1;
            int day = Integer.valueOf(matcher.group(3));
            int hour = Integer.valueOf(matcher.group(4));
            int minute = Integer.valueOf(matcher.group(5));
            int second = Integer.valueOf(matcher.group(6));
            GregorianCalendar cal = new GregorianCalendar(year, month, day, hour, minute, second);
            mValue = cal.getTime();
        }
    }
}

79. Media#escapeImages()

Project: Anki-Android
Source File: Media.java
View license
/**
     * Percent-escape UTF-8 characters in local image filenames.
     * @param string The string to search for image references and escape the filenames.
     * @return The string with the filenames of any local images percent-escaped as UTF-8.
     */
public String escapeImages(String string, boolean unescape) {
    for (Pattern p : Arrays.asList(fImgRegExpQ, fImgRegExpU)) {
        Matcher m = p.matcher(string);
        // NOTE: python uses the named group 'fname'. Java doesn't have named groups, so we have to determine
        // the index based on which pattern we are using
        int fnameIdx = p == fImgRegExpU ? 2 : 3;
        while (m.find()) {
            String tag = m.group(0);
            String fname = m.group(fnameIdx);
            if (fRemotePattern.matcher(fname).find()) {
            //dont't do any escaping if remote image
            } else {
                if (unescape) {
                    string = string.replace(tag, tag.replace(fname, Uri.decode(fname)));
                } else {
                    string = string.replace(tag, tag.replace(fname, Uri.encode(fname)));
                }
            }
        }
    }
    return string;
}

80. IvyModuleDescriptorFile#getConfigurationNames()

View license
public String[] getConfigurationNames() {
    Pattern p = CONFIGURATIONS_START_PATTERN;
    Matcher m = p.matcher(getDoc());
    if (m.find()) {
        int start = m.end();
        p = CONFIGURATIONS_END_PATTERN;
        m = p.matcher(getDoc());
        int end = getDoc().length();
        if (m.find(start)) {
            end = m.start();
        }
        p = CONF_PATTERN;
        m = p.matcher(getDoc());
        List ret = new ArrayList();
        for (boolean found = m.find(start); found && m.end() < end; found = m.find()) {
            ret.add(m.group(1));
        }
        return (String[]) ret.toArray(new String[ret.size()]);
    } else {
        return new String[] { "default" };
    }
}

81. LogicalPlan#convertRegexToList()

Project: apex-core
Source File: LogicalPlan.java
View license
/**
   * Convert regex in Affinity Rule to list of operators
   * Regex should match at least 2 operators, otherwise rule is not applied
   * @param operatorNames
   * @param rule
   */
public void convertRegexToList(List<String> operatorNames, AffinityRule rule) {
    List<String> operators = new LinkedList<String>();
    Pattern p = Pattern.compile(rule.getOperatorRegex());
    for (String name : operatorNames) {
        if (p.matcher(name).matches()) {
            operators.add(name);
        }
    }
    rule.setOperatorRegex(null);
    if (operators.size() <= 1) {
        LOG.warn("Regex should match at least 2 operators to add affinity rule. Ignoring rule");
    } else {
        rule.setOperatorsList(operators);
    }
}

82. DTLoggerFactory#getClassesMatching()

Project: apex-core
Source File: DTLoggerFactory.java
View license
public synchronized ImmutableMap<String, String> getClassesMatching(@Nonnull String searchKey) {
    Pattern searchPattern = Pattern.compile(searchKey);
    Map<String, String> matchedClasses = Maps.newHashMap();
    @SuppressWarnings("unchecked") Enumeration<Logger> loggerEnumeration = LogManager.getCurrentLoggers();
    while (loggerEnumeration.hasMoreElements()) {
        Logger logger = loggerEnumeration.nextElement();
        if (searchPattern.matcher(logger.getName()).matches()) {
            Level level = logger.getLevel();
            matchedClasses.put(logger.getName(), level == null ? "" : level.toString());
        }
    }
    return ImmutableMap.copyOf(matchedClasses);
}

83. Highlighter#highlight()

Project: apg
Source File: Highlighter.java
View license
public Spannable highlight(String text) {
    Spannable highlight = Spannable.Factory.getInstance().newSpannable(text);
    if (mQuery == null) {
        return highlight;
    }
    Pattern pattern = Pattern.compile("(?i)(" + mQuery.trim().replaceAll("\\s+", "|") + ")");
    Matcher matcher = pattern.matcher(text);
    while (matcher.find()) {
        highlight.setSpan(new ForegroundColorSpan(mContext.getResources().getColor(R.color.emphasis)), matcher.start(), matcher.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
    return highlight;
}

84. PluginExclusion#buildPluginExclusion()

View license
/**
     * Builds @PluginExclusion from the given configuration string.
     * @param exclusionString The exclusion string from the configuration.
     * @return A new @PluginExclusion object.
     */
public static PluginExclusion buildPluginExclusion(String exclusionString) {
    Pattern pattern = Pattern.compile("(.*):(.*)");
    Matcher matcher = pattern.matcher(exclusionString);
    PluginExclusion pluginExclusion = null;
    if (matcher.matches()) {
        String pluginName = matcher.group(1);
        String exclude = matcher.group(2);
        List<String> exclusions = Arrays.asList(exclude.split(","));
        pluginExclusion = new PluginExclusion(pluginName, exclusions);
    } else {
        // If no sources provided, we assume that the entire plugin sources should be excluded.
        pluginExclusion = new PluginExclusion(exclusionString);
    }
    return pluginExclusion;
}

85. Banner#injectVersion()

Project: archiva
Source File: Banner.java
View license
public static String injectVersion(String text, String version) {
    Pattern pat = Pattern.compile("#{2,}");
    Matcher mat = pat.matcher(text);
    StringBuilder ret = new StringBuilder();
    int off = 0;
    while (mat.find(off)) {
        ret.append(text.substring(off, mat.start()));
        String repl = mat.group();
        ret.append(StringUtils.center(version, repl.length()));
        off = mat.end();
    }
    ret.append(text.substring(off));
    return ret.toString();
}

86. ArtifactManager#determineVersionViaClasspath()

View license
private String determineVersionViaClasspath(String groupId, String artifactId, String packaging, String classifier) {
    String regexp = ".*" + artifactId + "-(.+)" + (classifier.length() == 0 ? "" : "-" + classifier) + "." + packaging;
    Pattern pattern = Pattern.compile(regexp);
    for (final String element : System.getProperty("java.class.path").split(File.pathSeparator)) {
        Matcher matcher = pattern.matcher(element);
        if (matcher.matches()) {
            return matcher.group(1);
        }
    }
    return null;
}

87. PatternOptionHandler#parseArguments()

Project: args4j
Source File: PatternOptionHandler.java
View license
@Override
public int parseArguments(Parameters params) throws CmdLineException {
    String s = params.getParameter(0);
    Pattern p;
    try {
        p = Pattern.compile(s);
    } catch (PatternSyntaxException x) {
        throw new CmdLineException(owner, Messages.ILLEGAL_PATTERN.format(option.toString(), s));
    }
    setter.addValue(p);
    return 1;
}

88. SystemConfiguration#toString()

Project: Argus
Source File: SystemConfiguration.java
View license
/**
     * Returns the list of configured properties and their values.
     *
     * @return  The list of configured properties and their values.
     */
@Override
public synchronized String toString() {
    Properties allProperties = new Properties();
    allProperties.putAll(this);
    for (Property property : Property.values()) {
        allProperties.putIfAbsent(property.key(), property.defaultValue());
    }
    StringBuilder sb = new StringBuilder();
    sb.append("Using the following configured values:\n");
    Pattern pattern = Pattern.compile("pwd|secret|password|passwd|token");
    Set<String> names = new TreeSet<>(allProperties.stringPropertyNames());
    names.stream().forEach(( name) -> {
        String value = pattern.matcher(name).find() ? "********" : allProperties.get(name).toString();
        sb.append("\t").append(name).append(" : ").append(value).append("\n");
    });
    return sb.toString();
}

89. ClassNamePattern#accepts()

Project: asakusafw
Source File: ClassNamePattern.java
View license
/**
     * Returns whether this accepts the target class name or not.
     * @param name the target class name
     * @return [email protected] true} if this accepts the target class name, otherwise [email protected] false}
     */
public boolean accepts(String name) {
    if (patterns.length == 0) {
        return defaultAccepts;
    }
    for (Pattern pattern : patterns) {
        if (pattern.matcher(name).matches()) {
            if (LOG.isDebugEnabled()) {
                //$NON-NLS-1$
                LOG.debug("matched: {} ({})", name, pattern);
            }
            return true;
        }
    }
    return false;
}

90. GenerateCreateTableTask#collect()

View license
private ClassCollector collect(Configuration configuration) {
    final Pattern pattern = configuration.acceptTableNames;
    ClassCollector collector = new ClassCollector(configuration.classLoader, new Selector() {

        @Override
        public boolean accept(Class<?> aClass) {
            TableInfo info = getSchema(aClass);
            if (info == null) {
                return false;
            }
            if (pattern != null) {
                if (pattern.matcher(info.getName()).matches() == false) {
                    //$NON-NLS-1$
                    LOG.debug("filtered table: {}", info.getName());
                    return false;
                }
            }
            return true;
        }
    });
    return collector;
}

91. ParquetFileFormatTest#checkDecimal()

View license
private void checkDecimal(String file) throws IOException, InterruptedException {
    Pattern p = Pattern.compile("decimal-(\\d+)_(\\d+)-(.+)\\.parquet");
    Matcher matcher = p.matcher(file);
    assertThat(matcher.matches(), is(true));
    int precision = Integer.parseInt(matcher.group(1));
    int scale = Integer.parseInt(matcher.group(2));
    WithDecimal buf = new WithDecimal();
    ParquetFileFormat<WithDecimal> format = format(WithDecimal.class, Collections.singletonMap("value", ValueSerdeFactory.getDecimal(precision, scale)));
    try (ModelInput<WithDecimal> input = load(format, file)) {
        assertThat(input.readTo(buf), is(true));
        assertThat(input.readTo(new WithDecimal()), is(false));
    }
    BigDecimal expected = new BigDecimal(matcher.group(3).replace('_', '.'));
    assertThat(buf.value, is(new DecimalOption(expected)));
}

92. ParquetFileFormatTest#checkDateTime()

View license
@SuppressWarnings("deprecation")
private void checkDateTime(String file) throws IOException, InterruptedException {
    Pattern p = Pattern.compile("timestamp-(\\d+)-(\\d+)-(\\d+)-(\\d+)-(\\d+)-(\\d+)\\.parquet");
    Matcher matcher = p.matcher(file);
    assertThat(matcher.matches(), is(true));
    WithDateTime buf = new WithDateTime();
    try (ModelInput<WithDateTime> input = load(WithDateTime.class, file)) {
        assertThat(input.readTo(buf), is(true));
        assertThat(input.readTo(new WithDateTime()), is(false));
    }
    // fix timezone
    buf.value.modify(buf.value.get().getElapsedSeconds() + TESTDATA_TIMEZONE_OFFSET - LOCAL_TIMEZONE_OFFSET);
    DateTime expected = new DateTime(Integer.parseInt(matcher.group(1)), Integer.parseInt(matcher.group(2)), Integer.parseInt(matcher.group(3)), Integer.parseInt(matcher.group(4)), Integer.parseInt(matcher.group(5)), Integer.parseInt(matcher.group(6)));
    assertThat(buf.value, is(new DateTimeOption(expected)));
}

93. ParquetFileFormatTest#checkDate()

View license
private void checkDate(String file) throws IOException, InterruptedException {
    Pattern p = Pattern.compile("date-(\\d+)-(\\d+)-(\\d+)\\.parquet");
    Matcher matcher = p.matcher(file);
    assertThat(matcher.matches(), is(true));
    WithDate buf = new WithDate();
    try (ModelInput<WithDate> input = load(WithDate.class, file)) {
        assertThat(input.readTo(buf), is(true));
        assertThat(input.readTo(new WithDate()), is(false));
    }
    Date expected = new Date(Integer.parseInt(matcher.group(1)), Integer.parseInt(matcher.group(2)), Integer.parseInt(matcher.group(3)));
    assertThat(buf.value, is(new DateOption(expected)));
}

94. Strings_assertDoesNotMatch_Pattern_Test#should_fail_if_actual_matches_Pattern()

View license
@Test
public void should_fail_if_actual_matches_Pattern() {
    AssertionInfo info = someInfo();
    Pattern pattern = matchAnything();
    try {
        strings.assertDoesNotMatch(info, actual, pattern);
    } catch (AssertionError e) {
        verify(failures).failure(info, shouldNotMatch(actual, pattern.pattern()));
        return;
    }
    failBecauseExpectedAssertionErrorWasNotThrown();
}

95. Strings_assertDoesNotMatch_Pattern_Test#should_fail_if_actual_matches_Pattern_whatever_custom_comparison_strategy_is()

View license
@Test
public void should_fail_if_actual_matches_Pattern_whatever_custom_comparison_strategy_is() {
    AssertionInfo info = someInfo();
    Pattern pattern = matchAnything();
    try {
        stringsWithCaseInsensitiveComparisonStrategy.assertDoesNotMatch(info, actual, pattern);
    } catch (AssertionError e) {
        verify(failures).failure(info, shouldNotMatch(actual, pattern.pattern()));
        return;
    }
    failBecauseExpectedAssertionErrorWasNotThrown();
}

96. CqlColumnFamilyDefinitionImpl#processCompositeComparatorSpec()

View license
private void processCompositeComparatorSpec(String comparatorSpec) {
    // e.g  CompositeType(UTF8Type, LongType, UTF8Type)
    String regex = "[\\(,\\)]";
    Pattern pattern = Pattern.compile(regex);
    String[] parts = pattern.split(comparatorSpec);
    int colIndex = 1;
    for (int i = 1; i < parts.length; i++) {
        String componentTypeString = parts[i].trim();
        ColumnDefinition column = new CqlColumnDefinitionImpl().setName("column" + colIndex++).setValidationClass(componentTypeString);
        clusteringKeyList.add(column);
    }
}

97. Rule#ruleApplies()

Project: ATLauncher
Source File: Rule.java
View license
public boolean ruleApplies() {
    if (this.os == null) {
        return true;
    }
    if (this.os.getName() != null && this.os.getName() != OperatingSystem.getOS()) {
        return false;
    }
    if (this.os.getVersion() == null) {
        return true;
    }
    Pattern pattern = Pattern.compile(this.os.getVersion());
    Matcher matcher = pattern.matcher(OperatingSystem.getVersion());
    return matcher.matches();
}

98. UiElementBoundsParser#parse()

View license
/**
     * Converts a UI element bounds in the format <b>[startX,startY][endX,endY]</b> (fetched from the UI XML file) to a
     * Pair<Point, Point;> format.
     * 
     * @param bounds
     *        String containing UiElement bounds to be parsed.
     * @return Bounds pair containing the UiElement bounds.
     */
public static Bounds parse(String bounds) {
    final String BOUNDS_STRING_PATTERN = "\\[(-*\\d+),(-*\\d+)\\]\\[(-*\\d+),(-*\\d+)\\]";
    final Pattern BOUNDS_PATTERN = Pattern.compile(BOUNDS_STRING_PATTERN);
    final Matcher BOUNDS_MATCHER = BOUNDS_PATTERN.matcher(bounds);
    if (BOUNDS_MATCHER.find()) {
        int firstPointX = Integer.parseInt(BOUNDS_MATCHER.group(1));
        int firstPointY = Integer.parseInt(BOUNDS_MATCHER.group(2));
        Point first = new Point(firstPointX, firstPointY);
        int secondPointX = Integer.parseInt(BOUNDS_MATCHER.group(3));
        int secondPointY = Integer.parseInt(BOUNDS_MATCHER.group(4));
        Point second = new Point(secondPointX, secondPointY);
        Bounds result = new Bounds(first, second);
        return result;
    } else {
        String message = String.format("' %s ' is not in the required bounds format.", bounds);
        LOGGER.error(message);
        throw new IllegalArgumentException(message);
    }
}

99. CompilationErrorsTest#testPrimitiveArrayWarning()

Project: auto
Source File: CompilationErrorsTest.java
View license
public void testPrimitiveArrayWarning() throws Exception {
    String testSourceCode = Joiner.on('\n').join("package foo.bar;", "import com.google.auto.value.AutoValue;", "@AutoValue", "public abstract class Baz {", "  public abstract byte[] bytes();", "  public static Baz create(byte[] bytes) {", "    return new AutoValue_Baz(bytes);", "  }", "}");
    Pattern warningPattern = Pattern.compile("An @AutoValue property that is a primitive array returns the original array");
    ImmutableTable<Diagnostic.Kind, Integer, Pattern> expectedDiagnostics = ImmutableTable.of(Diagnostic.Kind.WARNING, 5, warningPattern);
    assertCompilationResultIs(expectedDiagnostics, ImmutableList.of(testSourceCode));
}

100. CompilationErrorsTest#testPrimitiveArrayWarningFromParent()

Project: auto
Source File: CompilationErrorsTest.java
View license
public void testPrimitiveArrayWarningFromParent() throws Exception {
    // If the array-valued property is defined by an ancestor then we shouldn't try to attach
    // the warning to the method that defined it, but rather to the @AutoValue class itself.
    String testSourceCode = Joiner.on('\n').join("package foo.bar;", "import com.google.auto.value.AutoValue;", "public abstract class Baz {", "  public abstract byte[] bytes();", "", "  @AutoValue", "  public abstract static class BazChild extends Baz {", "    public static BazChild create(byte[] bytes) {", "      return new AutoValue_Baz_BazChild(bytes);", "    }", "  }", "}");
    Pattern warningPattern = Pattern.compile("An @AutoValue property that is a primitive array returns the original array" + ".*foo\\.bar\\.Baz\\.bytes");
    ImmutableTable<Diagnostic.Kind, Integer, Pattern> expectedDiagnostics = ImmutableTable.of(Diagnostic.Kind.WARNING, 7, warningPattern);
    assertCompilationResultIs(expectedDiagnostics, ImmutableList.of(testSourceCode));
}