java.util.regex.Matcher

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

1. GitModificationParser#processLine()

Project: gocd
Source File: GitModificationParser.java
View license
public void processLine(String line) {
    Matcher matcher = COMMIT_PATTERN.matcher(line);
    if (matcher.matches()) {
        modifications.add(new Modification("", "", null, null, matcher.group(1)));
    }
    Matcher authorMatcher = AUTHOR_PATTERN.matcher(line);
    if (authorMatcher.matches()) {
        modifications.getLast().setUserName(authorMatcher.group(1));
    }
    Matcher dateMatcher = DATE_PATTERN.matcher(line);
    if (dateMatcher.matches()) {
        modifications.getLast().setModifiedTime(DateUtils.parseISO8601(dateMatcher.group(1)));
    }
    Matcher commentMatcher = COMMENT_PATTERN.matcher(line);
    if (commentMatcher.matches()) {
        Modification last = modifications.getLast();
        String comment = last.getComment();
        if (!comment.isEmpty())
            comment += "\n";
        last.setComment(comment + commentMatcher.group(1));
    }
}

2. LaTeX#mungeQA()

Project: Anki-Android
Source File: LaTeX.java
View license
/**
     * Convert HTML with embedded latex tags to image links.
     * NOTE: Unlike the original python version of this method, only two parameters are required
     * in AnkiDroid. The omitted parameters are used to generate LaTeX images. AnkiDroid does not
     * support the generation of LaTeX media and the provided parameters are sufficient for all
     * other cases.
     */
public static String mungeQA(String html, Collection col) {
    StringBuffer sb = new StringBuffer();
    Matcher matcher = sStandardPattern.matcher(html);
    while (matcher.find()) {
        matcher.appendReplacement(sb, _imgLink(col, matcher.group(1)));
    }
    matcher.appendTail(sb);
    matcher = sExpressionPattern.matcher(sb.toString());
    sb = new StringBuffer();
    while (matcher.find()) {
        matcher.appendReplacement(sb, _imgLink(col, "$" + matcher.group(1) + "$"));
    }
    matcher.appendTail(sb);
    matcher = sMathPattern.matcher(sb.toString());
    sb = new StringBuffer();
    while (matcher.find()) {
        matcher.appendReplacement(sb, _imgLink(col, "\\begin{displaymath}" + matcher.group(1) + "\\end{displaymath}"));
    }
    matcher.appendTail(sb);
    return sb.toString();
}

3. LogMessageParser#parse()

Project: caliper
Source File: LogMessageParser.java
View license
@Override
public LogMessage parse(CharSequence text) {
    // TODO(gak): do this stuff in terms of CharSequence instead of String
    String string = text.toString();
    Matcher gcMatcher = GC_PATTERN.matcher(string);
    if (gcMatcher.matches()) {
        return new GcLogMessage("Full".equals(gcMatcher.group(1)) ? GcLogMessage.Type.FULL : GcLogMessage.Type.INCREMENTAL, ShortDuration.of(BigDecimal.valueOf(Double.parseDouble(gcMatcher.group(2))), SECONDS));
    }
    Matcher jitMatcher = JIT_PATTERN.matcher(string);
    if (jitMatcher.matches()) {
        return new HotspotLogMessage();
    }
    Matcher vmOptionMatcher = VM_OPTION_PATTERN.matcher(string);
    if (vmOptionMatcher.matches()) {
        return new VmOptionLogMessage(vmOptionMatcher.group(2), vmOptionMatcher.group(3));
    }
    return null;
}

4. LogParseUtil#parseUserFromUGI()

Project: Eagle
Source File: LogParseUtil.java
View license
/**
     * @param ugi UGI field of audit log
     * @return resultToMetrics user from UGI field of audit log
     */
public static String parseUserFromUGI(String ugi) {
    if (ugi == null)
        return null;
    String newugi = ugi.trim();
    Matcher defaultMatcher = UGI_PATTERN_DEFAULT.matcher(newugi);
    if (defaultMatcher.matches()) {
        return defaultMatcher.group(1);
    }
    Matcher sysMatcher = UGI_PATTERN_SYSTEM.matcher(newugi);
    if (sysMatcher.matches()) {
        return sysMatcher.group(1);
    }
    Matcher viaMatcher = UGI_PATTERN_WITHBLANK.matcher(newugi);
    if (viaMatcher.matches()) {
        return viaMatcher.group(1);
    }
    return newugi;
}

5. PyRequirement#parseVcsProjectUrl()

View license
@Nullable
private static PyRequirement parseVcsProjectUrl(@NotNull String line) {
    final Matcher vcsMatcher = VCS_PROJECT_URL.matcher(line);
    if (vcsMatcher.matches()) {
        return createVcsRequirement(vcsMatcher);
    }
    final Matcher gitMatcher = GIT_PROJECT_URL.matcher(line);
    if (gitMatcher.matches()) {
        return createVcsRequirement(gitMatcher);
    }
    final Matcher bzrMatcher = BZR_PROJECT_URL.matcher(line);
    if (bzrMatcher.matches()) {
        return createVcsRequirement(bzrMatcher);
    }
    return null;
}

6. KeywordExtractor#tokenizeWithSpaces()

Project: lucida
Source File: KeywordExtractor.java
View license
/**
	 * A rule-based tokenizer used to extract keywords for a query. This
	 * tokenizer is conservative, e.g. it does not split "F16" or "1,000.00".
	 * 
	 * @param text text to tokenize
	 * @return string of space-delimited tokens
	 */
public static String tokenizeWithSpaces(String text) {
    String rep;
    Matcher m1 = DELIMS1.matcher(text);
    while (m1.find()) {
        rep = " " + m1.group(0) + " ";
        text = text.replace(m1.group(0), rep);
    }
    Matcher m2 = DELIMS2.matcher(text);
    while (m2.find()) {
        rep = m2.group(1) + " " + m2.group(2) + " " + m2.group(3);
        text = text.replace(m2.group(0), rep);
    }
    Matcher m3 = DELIMS3.matcher(text);
    if (m3.find()) {
        rep = " " + m3.group(0);
        text = text.substring(0, text.length() - 1) + rep;
    }
    text = text.replaceAll("\\s++", " ").trim();
    return text;
}

7. SchemaRetriever#idFrom()

Project: modeshape
Source File: SchemaRetriever.java
View license
@Override
protected String idFrom(String path) {
    Matcher namedSchemaMatcher = SCHEMA_PATH_PATTERN.matcher(path);
    if (namedSchemaMatcher.matches()) {
        return documentId(namedSchemaMatcher.group(1), namedSchemaMatcher.group(2), namedSchemaMatcher.group(3), false, false);
    }
    Matcher tablesMatcher = TABLES_PATH_PATTERN.matcher(path);
    if (tablesMatcher.matches()) {
        return documentId(tablesMatcher.group(1), tablesMatcher.group(2), tablesMatcher.group(3), true, false);
    }
    Matcher proceduresMatcher = PROCEDURES_PATH_PATTERN.matcher(path);
    if (proceduresMatcher.matches()) {
        return documentId(proceduresMatcher.group(1), proceduresMatcher.group(2), proceduresMatcher.group(3), false, true);
    }
    return null;
}

8. DCMTools#validateSIPAddress()

Project: DataCenterManager
Source File: DCMTools.java
View license
public static String validateSIPAddress(String text) {
    StringBuffer finaltext = new StringBuffer("");
    StringBuffer newtext = new StringBuffer("");
    // Stage 1
    Pattern pattern = Pattern.compile("[^\\w\\-\\@\\:\\<\\>\\&\\.\\' ]");
    Matcher matcher = pattern.matcher(text);
    newtext = new StringBuffer();
    while (matcher.find()) {
        matcher.appendReplacement(newtext, "");
    }
    matcher.appendTail(newtext);
    // Stage 2
    pattern = Pattern.compile("\\'");
    matcher = pattern.matcher(newtext);
    finaltext = new StringBuffer();
    while (matcher.find()) {
        matcher.appendReplacement(finaltext, "\\\\\'");
    }
    matcher.appendTail(finaltext);
    return finaltext.toString();
}

9. TEIFormatter#getSectionNumber()

Project: grobid
Source File: TEIFormatter.java
View license
private Pair<String, String> getSectionNumber(String text) {
    Matcher m1 = BasicStructureBuilder.headerNumbering1.matcher(text);
    Matcher m2 = BasicStructureBuilder.headerNumbering2.matcher(text);
    Matcher m3 = BasicStructureBuilder.headerNumbering3.matcher(text);
    Matcher m = null;
    String numb = null;
    if (m1.find()) {
        numb = m1.group(0);
        m = m1;
    } else if (m2.find()) {
        numb = m2.group(0);
        m = m2;
    } else if (m3.find()) {
        numb = m3.group(0);
        m = m3;
    }
    if (numb != null) {
        text = text.replace(numb, "").trim();
        numb = numb.replace(" ", "");
        return new Pair<>(text, numb);
    } else {
        return null;
    }
}

10. Node#validateName()

Project: nodebox
Source File: Node.java
View license
/**
     * Checks if the given name would be valid for this node.
     *
     * @param name the name to check.
     * @throws InvalidNameException if the name was invalid.
     */
public static void validateName(String name) throws InvalidNameException {
    Matcher m1 = NODE_NAME_PATTERN.matcher(name);
    Matcher m2 = DOUBLE_UNDERSCORE_PATTERN.matcher(name);
    Matcher m3 = RESERVED_WORD_PATTERN.matcher(name);
    if (!m1.matches()) {
        throw new InvalidNameException(null, name, "Names can only contain lowercase letters, numbers, and the underscore. Names cannot be longer than 29 characters.");
    }
    if (m2.matches()) {
        throw new InvalidNameException(null, name, "Names starting with double underscore are reserved for internal use.");
    }
    if (m3.matches()) {
        throw new InvalidNameException(null, name, "Names cannot be a reserved word (network, node).");
    }
}

11. VoipStormTools#validateSIPAddress()

Project: VoipStorm
Source File: VoipStormTools.java
View license
/**
     *
     * @param text
     * @return
     */
public static String validateSIPAddress(String text) {
    StringBuffer finaltext = new StringBuffer("");
    StringBuffer newtext = new StringBuffer("");
    // Stage 1
    Pattern pattern = Pattern.compile("[^\\w\\-\\@\\:\\<\\>\\&\\.\\' ]");
    Matcher matcher = pattern.matcher(text);
    newtext = new StringBuffer();
    while (matcher.find()) {
        matcher.appendReplacement(newtext, "");
    }
    matcher.appendTail(newtext);
    // Stage 2
    pattern = Pattern.compile("\\'");
    matcher = pattern.matcher(newtext);
    finaltext = new StringBuffer();
    while (matcher.find()) {
        matcher.appendReplacement(finaltext, "\\\\\'");
    }
    matcher.appendTail(finaltext);
    return finaltext.toString();
}

12. InterfaceSearchAddress#getMatcher()

Project: Aeron
Source File: InterfaceSearchAddress.java
View license
private static Matcher getMatcher(CharSequence cs) {
    final Matcher ipV4Matcher = IPV4_ADDRESS_PATTERN.matcher(cs);
    if (ipV4Matcher.matches()) {
        return ipV4Matcher;
    }
    final Matcher ipV6Matcher = IPV6_ADDRESS_PATTERN.matcher(cs);
    if (ipV6Matcher.matches()) {
        return ipV6Matcher;
    }
    throw new IllegalArgumentException("Invalid search address: " + cs);
}

13. VersionRangeMatcher#accept()

Project: ant-ivy
Source File: VersionRangeMatcher.java
View license
public boolean accept(ModuleRevisionId askedMrid, ModuleRevisionId foundMrid) {
    String revision = askedMrid.getRevision();
    Matcher m;
    m = FINITE_RANGE.matcher(revision);
    if (m.matches()) {
        String lower = m.group(1);
        String upper = m.group(2);
        return isUpper(askedMrid, lower, foundMrid, revision.startsWith(OPEN_INC)) && isLower(askedMrid, upper, foundMrid, revision.endsWith(CLOSE_INC));
    }
    m = LOWER_INFINITE_RANGE.matcher(revision);
    if (m.matches()) {
        String upper = m.group(1);
        return isLower(askedMrid, upper, foundMrid, revision.endsWith(CLOSE_INC));
    }
    m = UPPER_INFINITE_RANGE.matcher(revision);
    if (m.matches()) {
        String lower = m.group(1);
        return isUpper(askedMrid, lower, foundMrid, revision.startsWith(OPEN_INC));
    }
    return false;
}

14. TranslationCheck#extractBaseName()

Project: checkstyle
Source File: TranslationCheck.java
View license
/**
     * Extracts the base name (the unique prefix) of resource bundle from translation file name.
     * For example "messages" is the base name of "messages.properties",
     * "messages_de_AT.properties", "messages_en.properties", etc.
     * @param fileName the fully qualified name of the translation file.
     * @return the extracted base name.
     */
private static String extractBaseName(String fileName) {
    final String regexp;
    final Matcher languageCountryVariantMatcher = LANGUAGE_COUNTRY_VARIANT_PATTERN.matcher(fileName);
    final Matcher languageCountryMatcher = LANGUAGE_COUNTRY_PATTERN.matcher(fileName);
    final Matcher languageMatcher = LANGUAGE_PATTERN.matcher(fileName);
    if (languageCountryVariantMatcher.matches()) {
        regexp = LANGUAGE_COUNTRY_VARIANT_PATTERN.pattern();
    } else if (languageCountryMatcher.matches()) {
        regexp = LANGUAGE_COUNTRY_PATTERN.pattern();
    } else if (languageMatcher.matches()) {
        regexp = LANGUAGE_PATTERN.pattern();
    } else {
        regexp = DEFAULT_TRANSLATION_REGEXP;
    }
    // We use substring(...) insead of replace(...), so that the regular expression does
    // not have to be compiled each time it is used inside 'replace' method.
    final String removePattern = regexp.substring("^.+".length(), regexp.length());
    return fileName.replaceAll(removePattern, "");
}

15. GoogleCodingConvention#getPackageName()

View license
/**
   * [email protected]}
   *
   * <p>In Google code, the package name of a source file is its file path.
   * Exceptions: if a source file's parent directory is "test", "tests", or
   * "testing", that directory is stripped from the package name.
   * If a file is generated, strip the "genfiles" prefix to try
   * to match the package of the generating file.
   */
@Override
public String getPackageName(StaticSourceFile source) {
    String name = source.getName();
    Matcher genfilesMatcher = GENFILES_DIR.matcher(name);
    if (genfilesMatcher.find()) {
        name = genfilesMatcher.group(1);
    }
    Matcher m = PACKAGE_WITH_TEST_DIR.matcher(name);
    if (m.find()) {
        return m.group(1);
    } else {
        int lastSlash = name.lastIndexOf('/');
        return lastSlash == -1 ? "" : name.substring(0, lastSlash);
    }
}

16. ChineseSegmenterFeatureFactory#isEnglish()

View license
private static String isEnglish(String Ep, String Ec) {
    String chp = Ep;
    String chc = Ec;
    // previous char is [a-z]
    Matcher mp = patE.matcher(chp);
    //  current char is [a-z]
    Matcher mc = patE.matcher(chc);
    // previous char is [A-Z]
    Matcher mpC = patEC.matcher(chp);
    //  current char is [A-Z]
    Matcher mcC = patEC.matcher(chc);
    if (mp.matches() && mcC.matches()) {
        // [a-z][A-Z]
        return "BND";
    } else if (mp.matches() && mc.matches()) {
        // [a-z][a-z]
        return "ENG";
    } else if (mpC.matches() && mcC.matches()) {
        // [A-Z][A-Z]
        return "BCC";
    } else if (mp.matches() && !mc.matches() && !mcC.matches()) {
        // [a-z][^A-Za-z]
        return "e1";
    } else if (mc.matches() && !mp.matches() && !mpC.matches()) {
        // [^A-Za-z][a-z]
        return "e2";
    } else if (mpC.matches() && !mc.matches() && !mcC.matches()) {
        // [A-Z][^A-Za-z]
        return "e3";
    } else if (mcC.matches() && !mp.matches() && !mpC.matches()) {
        // [^A-Za-z][A-Z]
        return "e4";
    } else {
        return "";
    }
}

17. Gale2007ChineseSegmenterFeatureFactory#isEnglish()

View license
private static String isEnglish(String chp, String chc) {
    // previous char is [a-z]
    Matcher mp = patE.matcher(chp);
    //  current char is [a-z]
    Matcher mc = patE.matcher(chc);
    // previous char is [A-Z]
    Matcher mpC = patEC.matcher(chp);
    //  current char is [A-Z]
    Matcher mcC = patEC.matcher(chc);
    if (mp.matches() && mcC.matches()) {
        // [a-z][A-Z]
        return "BND";
    } else if (mp.matches() && mc.matches()) {
        // [a-z][a-z]
        return "ENG";
    } else if (mpC.matches() && mcC.matches()) {
        // [A-Z][A-Z]
        return "BCC";
    } else if (mp.matches() && !mc.matches() && !mcC.matches()) {
        // [a-z][^A-Za-z]
        return "e1";
    } else if (mc.matches() && !mp.matches() && !mpC.matches()) {
        // [^A-Za-z][a-z]
        return "e2";
    } else if (mpC.matches() && !mc.matches() && !mcC.matches()) {
        // [A-Z][^A-Za-z]
        return "e3";
    } else if (mcC.matches() && !mp.matches() && !mpC.matches()) {
        // [^A-Za-z][A-Z]
        return "e4";
    } else {
        return "";
    }
}

18. TdOperatorFactory#insertCommandStatement()

Project: digdag
Source File: TdOperatorFactory.java
View license
@VisibleForTesting
static String insertCommandStatement(String command, String original) {
    // try to insert command at "-- DIGDAG_INSERT_LINE" line
    Matcher ml = INSERT_LINE_PATTERN.matcher(original);
    if (ml.find()) {
        return ml.replaceFirst(ml.group(1) + command);
    }
    // try to insert command after header comments so that job list page
    // shows comments rather than INSERT or other non-informative commands
    Matcher mc = HEADER_COMMENT_BLOCK_PATTERN.matcher(original);
    if (mc.find()) {
        return mc.group(1) + "\n" + command + "\n" + mc.group(2);
    }
    // add command at the head
    return command + "\n" + original;
}

19. GalleryPageParser#parse()

Project: EhViewer
Source File: GalleryPageParser.java
View license
public static Result parse(String body) throws ParseException {
    Matcher m;
    Result result = new Result();
    m = PATTERN_IMAGE_URL.matcher(body);
    if (m.find()) {
        result.imageUrl = StringUtils.unescapeXml(StringUtils.trim(m.group(1)));
    }
    m = PATTERN_SKIP_HATH_KEY.matcher(body);
    if (m.find()) {
        result.skipHathKey = StringUtils.unescapeXml(StringUtils.trim(m.group(1)));
    }
    m = PATTERN_ORIGIN_IMAGE_URL.matcher(body);
    if (m.find()) {
        result.originImageUrl = StringUtils.unescapeXml(m.group(1)) + "fullimg.php" + StringUtils.unescapeXml(m.group(2));
    }
    if (!TextUtils.isEmpty(result.imageUrl)) {
        return result;
    } else {
        throw new ParseException("Parse image url and skip hath key error", body);
    }
}

20. OracleSqlStatementBuilder#cleanToken()

View license
@Override
protected String cleanToken(String token) {
    if (token.startsWith("'") && token.endsWith("'")) {
        return token;
    }
    Matcher beforeMatcher = KEYWORDS_BEFORE_STRING_LITERAL_REGEX.matcher(token);
    if (beforeMatcher.find()) {
        token = beforeMatcher.group(2);
    }
    Matcher afterMatcher = KEYWORDS_AFTER_STRING_LITERAL_REGEX.matcher(token);
    if (afterMatcher.find()) {
        token = afterMatcher.group(1);
    }
    return token;
}

21. LinkController#findLink()

Project: freeplane
Source File: LinkController.java
View license
public static String findLink(final String text) {
    final Matcher urlMatcher = urlPattern.matcher(text);
    if (urlMatcher.find()) {
        String link = urlMatcher.group();
        try {
            new URL(link).toURI();
            return link;
        } catch (final MalformedURLException e) {
            return null;
        } catch (final URISyntaxException e) {
            return null;
        }
    }
    final Matcher mailMatcher = mailPattern.matcher(text);
    if (mailMatcher.find()) {
        final String link = "mailto:" + mailMatcher.group();
        return link;
    }
    return null;
}

22. AntTestFailureDetector#consumeLine()

Project: gocd
Source File: AntTestFailureDetector.java
View license
public void consumeLine(String line) {
    Matcher suite = suitePattern.matcher(line);
    if (suite.matches()) {
        inSuite = true;
    }
    if (!inSuite)
        return;
    Matcher results = testResultPattern.matcher(line);
    if (results.matches()) {
        count += Integer.parseInt(results.group(1));
        failures += Integer.parseInt(results.group(2));
        errors += Integer.parseInt(results.group(3));
        totalTime += Float.parseFloat(results.group(4)) * 1000;
        inSuite = false;
    }
}

23. MavenConsoleAnnotator#eol()

View license
@Override
protected void eol(byte[] b, int len) throws IOException {
    String line = charset.decode(ByteBuffer.wrap(b, 0, len)).toString();
    // trim off CR/LF from the end
    line = trimEOL(line);
    // TODO:
    // we need more support for conveniently putting annotations in the middle of the line, not just at the beginning
    // we also need the ability for an extension point to have notes hook into the processing
    Matcher m = MavenMojoNote.PATTERN.matcher(line);
    if (m.matches())
        new MavenMojoNote().encodeTo(out);
    m = MavenWarningNote.PATTERN.matcher(line);
    if (m.find())
        new MavenWarningNote().encodeTo(out);
    m = MavenErrorNote.PATTERN.matcher(line);
    if (m.find())
        new MavenErrorNote().encodeTo(out);
    out.write(b, 0, len);
}

24. RFC3339Utils#parseUTC()

Project: incubator-streams
Source File: RFC3339Utils.java
View license
public static DateTime parseUTC(String toParse) {
    if (MILLIS.matcher(toParse).matches()) {
        return new DateTime(Long.valueOf(toParse), DateTimeZone.UTC);
    }
    if (UTC_STANDARD.matcher(toParse).matches()) {
        return parseUTC(UTC_STANDARD_FMT, toParse);
    }
    Matcher utc = UTC_SUB_SECOND.matcher(toParse);
    if (utc.matches()) {
        return parseUTC(getSubSecondFormat(utc.group(1), "'Z'"), toParse);
    }
    if (LOCAL_STANDARD.matcher(toParse).matches()) {
        return parseUTC(LOCAL_STANDARD_FMT, toParse);
    }
    Matcher local = LOCAL_SUB_SECOND.matcher(toParse);
    if (local.matches()) {
        return parseUTC(getSubSecondFormat(local.group(1), "Z"), toParse);
    }
    throw new IllegalArgumentException(String.format("Failed to parse date %s. Ensure format is RFC3339 Compliant", toParse));
}

25. TerminalSshModule#checkUnknownHost()

View license
private boolean checkUnknownHost(@NotNull String line) {
    Matcher unknownHostMatcher = UNKNOWN_HOST_MESSAGE.matcher(line);
    Matcher hostFingerPrintMatcher = HOST_FINGERPRINT_MESSAGE.matcher(line);
    Matcher acceptHostMatcher = ACCEPT_HOST_PROMPT.matcher(line);
    if (unknownHostMatcher.matches()) {
        unknownHost = unknownHostMatcher.group(1);
    } else if (hostFingerPrintMatcher.matches()) {
        fingerprintAlgorithm = hostFingerPrintMatcher.group(1);
        hostFingerprint = hostFingerPrintMatcher.group(2);
    } else if (acceptHostMatcher.matches()) {
        handleUnknownHost();
    }
    return unknownHostMatcher.matches() || hostFingerPrintMatcher.matches() || acceptHostMatcher.matches();
}

26. NumpyDocStringTypeProvider#getNumpyUnionType()

View license
@NotNull
public static List<String> getNumpyUnionType(@NotNull String typeString) {
    final Matcher arrayMatcher = NUMPY_ARRAY_PATTERN.matcher(typeString);
    if (arrayMatcher.matches()) {
        typeString = arrayMatcher.group(2);
    }
    Matcher matcher = NUMPY_UNION_PATTERN.matcher(typeString);
    if (matcher.matches()) {
        typeString = matcher.group(1);
    }
    return Arrays.asList(typeString.split(" *, *"));
}

27. RegexStoryParser#createNarrative()

Project: jbehave-core
Source File: RegexStoryParser.java
View license
private Narrative createNarrative(String narrative) {
    Matcher findingElements = findingNarrativeElements().matcher(narrative);
    if (findingElements.matches()) {
        String inOrderTo = findingElements.group(1).trim();
        String asA = findingElements.group(2).trim();
        String iWantTo = findingElements.group(3).trim();
        return new Narrative(inOrderTo, asA, iWantTo);
    }
    Matcher findingAlternativeElements = findingAlternativeNarrativeElements().matcher(narrative);
    if (findingAlternativeElements.matches()) {
        String asA = findingAlternativeElements.group(1).trim();
        String iWantTo = findingAlternativeElements.group(2).trim();
        String soThat = findingAlternativeElements.group(3).trim();
        return new Narrative("", asA, iWantTo, soThat);
    }
    return Narrative.EMPTY;
}

28. NTriple#escapeNTriple()

Project: jena
Source File: NTriple.java
View license
/**
	 * 
	 * Replace any non-legal char (or Z) with ZNN where NN are the hex codes
	 * in UTF-8
	 * @param anonymousID Is something that corresponds to an XMLName 
	 * @return an ascii string that is legal NTriple
	 */
public static String escapeNTriple(String anonymousID) {
    Matcher matcher = ntripleBnode.matcher(anonymousID);
    if (matcher.matches())
        return anonymousID;
    matcher.reset();
    StringBuilder rslt = new StringBuilder();
    int lastNotMatched = 0;
    while (matcher.find()) {
        String unmatched = anonymousID.substring(lastNotMatched, matcher.start());
        rslt.append(escapeUTF8(unmatched));
        lastNotMatched = matcher.end();
        rslt.append(matcher.group());
    }
    rslt.append(escapeUTF8(anonymousID.substring(lastNotMatched)));
    return rslt.toString();
}

29. Value#parse()

Project: lumify
Source File: Value.java
View license
public static Value parse(String valueRaw) {
    Matcher m = STRING_VALUE_PATTERN.matcher(valueRaw);
    if (m.matches()) {
        return new StringValue(m.group(1), m.group(2));
    }
    m = LINK_VALUE_PATTERN.matcher(valueRaw);
    if (m.matches()) {
        return new LinkValue(m.group(1));
    }
    m = OTHER_VALUE_PATTERN.matcher(valueRaw);
    if (m.matches()) {
        return new OtherValue(m.group(1), m.group(2));
    }
    throw new LumifyException("Could not parse value: " + valueRaw);
}

30. DataHostConfig#setHearbeatSQL()

Project: Mycat-Server
Source File: DataHostConfig.java
View license
public void setHearbeatSQL(String heartbeatSQL) {
    this.hearbeatSQL = heartbeatSQL;
    Matcher matcher = pattern.matcher(heartbeatSQL);
    if (matcher.find()) {
        isShowSlaveSql = true;
    }
    Matcher matcher2 = patternCluster.matcher(heartbeatSQL);
    if (matcher2.find()) {
        isShowClusterSql = true;
    }
}

31. CmsStringUtil#extractHtmlBody()

Project: opencms-core
Source File: CmsStringUtil.java
View license
public static String extractHtmlBody(String content) {
    Matcher startMatcher = BODY_START_PATTERN.matcher(content);
    Matcher endMatcher = BODY_END_PATTERN.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. 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);
}

33. ZibaseListener#extractIdFromZbResponse()

Project: openhab
Source File: ZibaseListener.java
View license
/**
     * Get Item's id from zibase log
     * 
     * @param zbResponseStr
     * @return
     */
protected String extractIdFromZbResponse(String zbResponseStr) {
    Matcher matcher = ZibaseListener.X10CHACONPATTERN.matcher(zbResponseStr);
    if (matcher.find()) {
        return matcher.group(1);
    }
    matcher = ZibaseListener.SCENARIOPATTERN.matcher(zbResponseStr);
    if (matcher.find()) {
        return matcher.group(1);
    }
    matcher = ZibaseListener.RADIODIDPATTERM.matcher(zbResponseStr);
    if (matcher.find()) {
        return matcher.group(2);
    }
    return null;
}

34. OutputAnalyzer#firstMatch()

Project: openjdk
Source File: OutputAnalyzer.java
View license
/**
     * Get the captured group of the first string matching the pattern. stderr
     * is searched before stdout.
     *
     * @param pattern
     *            The multi-line pattern to match
     * @param group
     *            The group to capture
     * @return The matched string or null if no match was found
     */
public String firstMatch(String pattern, int group) {
    Matcher stderrMatcher = Pattern.compile(pattern, Pattern.MULTILINE).matcher(getStderr());
    Matcher stdoutMatcher = Pattern.compile(pattern, Pattern.MULTILINE).matcher(getStdout());
    if (stderrMatcher.find()) {
        return stderrMatcher.group(group);
    }
    if (stdoutMatcher.find()) {
        return stdoutMatcher.group(group);
    }
    return null;
}

35. OutputAnalyzer#firstMatch()

Project: openjdk
Source File: OutputAnalyzer.java
View license
/**
     * Get the captured group of the first string matching the pattern. stderr
     * is searched before stdout.
     *
     * @param pattern
     *            The multi-line pattern to match
     * @param group
     *            The group to capture
     * @return The matched string or null if no match was found
     */
public String firstMatch(String pattern, int group) {
    Matcher stderrMatcher = Pattern.compile(pattern, Pattern.MULTILINE).matcher(getStderr());
    Matcher stdoutMatcher = Pattern.compile(pattern, Pattern.MULTILINE).matcher(getStdout());
    if (stderrMatcher.find()) {
        return stderrMatcher.group(group);
    }
    if (stdoutMatcher.find()) {
        return stdoutMatcher.group(group);
    }
    return null;
}

36. ReadOnlyStyledDocument#fromString()

View license
public static <PS, S> ReadOnlyStyledDocument<PS, S> fromString(String str, PS paragraphStyle, S style) {
    Matcher m = LINE_TERMINATOR.matcher(str);
    int n = 1;
    while (m.find()) ++n;
    List<Paragraph<PS, S>> res = new ArrayList<>(n);
    int start = 0;
    m.reset();
    while (m.find()) {
        String s = str.substring(start, m.start());
        res.add(new Paragraph<>(paragraphStyle, s, style));
        start = m.end();
    }
    String last = str.substring(start);
    res.add(new Paragraph<>(paragraphStyle, last, style));
    return new ReadOnlyStyledDocument<>(res);
}

37. MotherlessRipper#getGID()

Project: ripme
Source File: MotherlessRipper.java
View license
@Override
public String getGID(URL url) throws MalformedURLException {
    Pattern p = Pattern.compile("^https?://(www\\.)?motherless\\.com/G([MVI]?[A-F0-9]{6,8}).*$");
    Matcher m = p.matcher(url.toExternalForm());
    if (m.matches()) {
        return m.group(m.groupCount());
    }
    p = Pattern.compile("^https?://(www\\.)?motherless\\.com/term/(images/|videos/)([a-zA-Z0-9%]+)$");
    m = p.matcher(url.toExternalForm());
    if (m.matches()) {
        return m.group(m.groupCount());
    }
    p = Pattern.compile("^https?://(www\\.)?motherless\\.com/g[iv]/([a-zA-Z0-9%\\-_]+)$");
    m = p.matcher(url.toExternalForm());
    if (m.matches()) {
        return m.group(m.groupCount());
    }
    throw new MalformedURLException("Expected URL format: http://motherless.com/GIXXXXXXX, got: " + url);
}

38. RedditRipper#getGID()

Project: ripme
Source File: RedditRipper.java
View license
@Override
public String getGID(URL url) throws MalformedURLException {
    // User
    Pattern p = Pattern.compile("^https?://[a-zA-Z0-9\\.]{0,4}reddit\\.com/(user|u)/([a-zA-Z0-9_\\-]{3,}).*$");
    Matcher m = p.matcher(url.toExternalForm());
    if (m.matches()) {
        return "user_" + m.group(m.groupCount());
    }
    // Post
    p = Pattern.compile("^https?://[a-zA-Z0-9\\.]{0,4}reddit\\.com/.*comments/([a-zA-Z0-9]{1,8}).*$");
    m = p.matcher(url.toExternalForm());
    if (m.matches()) {
        return "post_" + m.group(m.groupCount());
    }
    // Subreddit
    p = Pattern.compile("^https?://[a-zA-Z0-9\\.]{0,4}reddit\\.com/r/([a-zA-Z0-9_]{1,}).*$");
    m = p.matcher(url.toExternalForm());
    if (m.matches()) {
        return "sub_" + m.group(m.groupCount());
    }
    throw new MalformedURLException("Only accepts user pages, subreddits, or post, can't understand " + url);
}

39. DefaultAttributeValidationPolicy#parse()

View license
/**
	 * Validates attribute contained in the buffer and returns an LdapAttribute.
	 * <p>
	 * Ensures attributes meets one of three prescribed patterns for valid attributes:
	 * <ol>
	 * 	<li>A standard attribute pattern of the form: ATTR_ID[;options]: VALUE</li>
	 * 	<li>A Base64 attribute pattern of the form: ATTR_ID[;options]:: BASE64_VALUE</li>
	 * 	<li>A url attribute pattern of the form: ATTR_ID[;options]:< URL_VALUE</li>
	 * </ol>
	 * <p>
	 * Upon success an LdapAttribute object is returned.  
	 * 
	 * @param buffer [email protected]}
	 * @return [email protected]}
	 * @throws InvalidAttributeFormatException if the attribute does not meet one of the three patterns above
	 * or the attribute cannot be parsed.
	 */
public Attribute parse(String buffer) {
    log.trace("Parsing --> [" + buffer + "]");
    Matcher matcher = ATTRIBUTE_PATTERN.matcher(buffer);
    if (matcher.matches()) {
        //Is a regular attribute...			
        return parseStringAttribute(matcher);
    }
    matcher = BASE64_ATTRIBUTE_PATTERN.matcher(buffer);
    if (matcher.matches()) {
        //Is a base64 attribute...			
        return parseBase64Attribute(matcher);
    }
    matcher = URL_ATTRIBUTE_PATTERN.matcher(buffer);
    if (matcher.matches()) {
        //Is a URL attribute...			
        return parseUrlAttribute(matcher);
    }
    //default: no match.
    throw new InvalidAttributeFormatException("Not a valid attribute: [" + buffer + "]");
}

40. MatcherTest#testFindRegionChanged()

Project: teavm
Source File: MatcherTest.java
View license
@Test
public void testFindRegionChanged() {
    // Regression for HARMONY-625
    Pattern pattern = Pattern.compile("(?s).*");
    Matcher matcher = pattern.matcher("abcde");
    matcher.find();
    assertEquals("abcde", matcher.group());
    matcher = pattern.matcher("abcde");
    matcher.region(0, 2);
    matcher.find();
    assertEquals("ab", matcher.group());
}

41. GrblFirmwareSettingsDialog#addSetting()

View license
private void addSetting(String msg) {
    String setting;
    String value;
    String comment;
    Matcher matcher = this.settingNumPattern.matcher(msg);
    if (matcher.find()) {
        setting = matcher.group();
    } else {
        return;
    }
    matcher = this.settingValuePattern.matcher(msg);
    if (matcher.find()) {
        value = matcher.group(1);
    } else {
        return;
    }
    matcher = this.commentPattern.matcher(msg);
    if (matcher.find()) {
        comment = matcher.group();
    } else {
        return;
    }
    addSetting(setting, value, comment);
}

42. ConverterTextToHtml#linkifyText()

View license
private static void linkifyText(final String text, final StringBuffer outputBuffer) {
    String prepared = replaceAll(text, BITCOIN_URI_PATTERN, "<a href=\"$0\">$0</a>");
    Matcher m = Patterns.WEB_URL.matcher(prepared);
    while (m.find()) {
        int start = m.start();
        if (start == 0 || (start != 0 && text.charAt(start - 1) != '@')) {
            if (m.group().indexOf(':') > 0) {
                // With no URI-schema we may get "http:/" links with the second / missing
                m.appendReplacement(outputBuffer, "<a href=\"$0\">$0</a>");
            } else {
                m.appendReplacement(outputBuffer, "<a href=\"http://$0\">$0</a>");
            }
        } else {
            m.appendReplacement(outputBuffer, "$0");
        }
    }
    m.appendTail(outputBuffer);
}

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

44. Utils#quote()

Project: AngularBeans
Source File: Utils.java
View license
public static String quote(String string) {
    String quoted = jsonStringify(string);
    Matcher matcher = ESCAPABLE.matcher(quoted);
    StringBuffer escapedQuoted = new StringBuffer();
    while (matcher.find()) {
        matcher.appendReplacement(escapedQuoted, escapableLookup.get(matcher.group()));
    }
    matcher.appendTail(escapedQuoted);
    if (escapedQuoted.length() == 0) {
        return quoted;
    }
    return escapedQuoted.toString();
}

45. ChessFilter#fenToChessboard()

Project: Anki-Android
Source File: ChessFilter.java
View license
private String fenToChessboard(String text) {
    Boolean showBlack = false;
    Matcher mf = fFenPattern.matcher(text);
    StringBuffer sb = new StringBuffer();
    while (mf.find()) {
        if (mf.group(1) != null) {
            Matcher mo = fFenOrientationPattern.matcher(mf.group(1));
            if (mo.find() && mo.group(1) != null && mo.group(1).equalsIgnoreCase("black")) {
                showBlack = true;
            }
        }
        try {
            mf.appendReplacement(sb, "<script type=\"text/javascript\">document.write(" + String.format(Locale.US, fRenderFen, mf.group(2), showBlack) + ");</script>");
        } catch (Exception e) {
            Timber.e("ChessFilter exception: ", e);
        }
    }
    mf.appendTail(sb);
    return sb.toString();
}

46. Template#clozeText()

Project: Anki-Android
Source File: Template.java
View license
private static String clozeText(String txt, String ord, char type) {
    Matcher m = Pattern.compile(String.format(Locale.US, clozeReg, ord)).matcher(txt);
    if (!m.find()) {
        return "";
    }
    m.reset();
    StringBuffer repl = new StringBuffer();
    while (m.find()) {
        // replace chosen cloze with type
        if (type == 'q') {
            if (!TextUtils.isEmpty(m.group(3))) {
                m.appendReplacement(repl, "<span class=cloze>[$3]</span>");
            } else {
                m.appendReplacement(repl, "<span class=cloze>[...]</span>");
            }
        } else {
            m.appendReplacement(repl, "<span class=cloze>$1</span>");
        }
    }
    txt = m.appendTail(repl).toString();
    // and display other clozes normally
    return txt.replaceAll(String.format(Locale.US, clozeReg, "\\d+"), "$1");
}

47. Utils#entsToTxt()

Project: Anki-Android
Source File: Utils.java
View license
/**
     * Takes a string and replaces all the HTML symbols in it with their unescaped representation.
     * This should only affect substrings of the form &something; and not tags.
     * Internet rumour says that Html.fromHtml() doesn't cover all cases, but it doesn't get less
     * vague than that.
     * @param html The HTML escaped text
     * @return The text with its HTML entities unescaped.
     */
private static String entsToTxt(String html) {
    // entitydefs defines nbsp as \xa0 instead of a standard space, so we
    // replace it first
    html = html.replace(" ", " ");
    Matcher htmlEntities = htmlEntitiesPattern.matcher(html);
    StringBuffer sb = new StringBuffer();
    while (htmlEntities.find()) {
        htmlEntities.appendReplacement(sb, Html.fromHtml(htmlEntities.group()).toString());
    }
    htmlEntities.appendTail(sb);
    return sb.toString();
}

48. Utils#entsToTxt()

Project: Anki-Android
Source File: Utils.java
View license
/**
     * Takes a string and replaces all the HTML symbols in it with their unescaped representation.
     * This should only affect substrings of the form &something; and not tags.
     * Internet rumour says that Html.fromHtml() doesn't cover all cases, but it doesn't get less
     * vague than that.
     * @param html The HTML escaped text
     * @return The text with its HTML entities unescaped.
     */
private static String entsToTxt(String html) {
    // entitydefs defines nbsp as \xa0 instead of a standard space, so we
    // replace it first
    html = html.replace(" ", " ");
    Matcher htmlEntities = htmlEntitiesPattern.matcher(html);
    StringBuffer sb = new StringBuffer();
    while (htmlEntities.find()) {
        htmlEntities.appendReplacement(sb, Html.fromHtml(htmlEntities.group()).toString());
    }
    htmlEntities.appendTail(sb);
    return sb.toString();
}

49. IvySettingsFile#getClasspathUrls()

Project: ant-ivyde
Source File: IvySettingsFile.java
View license
public URL[] getClasspathUrls() {
    List urls = new ArrayList();
    Matcher m = CLASSPATH_URL_PATTERN.matcher(getDoc());
    while (m.find()) {
        try {
            urls.add(new URL(substitute(m.group(1))));
        } catch (MalformedURLException e) {
        }
    }
    m = CLASSPATH_FILE_PATTERN.matcher(getDoc());
    while (m.find()) {
        try {
            urls.add(new URL(substitute(m.group(1))));
        } catch (MalformedURLException e) {
            try {
                urls.add(new File(substitute(m.group(1))).toURI().toURL());
            } catch (MalformedURLException e1) {
            }
        }
    }
    return (URL[]) urls.toArray(new URL[urls.size()]);
}

50. JdbcStatement#trimSQL()

View license
private void trimSQL() {
    this.sql = this.sql.trim();
    Matcher m = PATTERN_WHITESPACE_BEGIN.matcher(this.sql);
    if (m.find()) {
        this.sql = this.sql.substring(m.end());
    }
    m = PATTERN_WHITESPACE_END.matcher(this.sql);
    if (m.find()) {
        this.sql = this.sql.substring(0, m.start());
    }
    if (this.sql.endsWith(";")) {
        this.sql = this.sql.substring(0, this.sql.length() - 1);
    }
}

51. CssSelectorNodeFilter#unescape()

Project: bboss
Source File: CssSelectorNodeFilter.java
View license
/**
     * Replace escape sequences in a string.
     * @param escaped The string to examine.
     * @return The argument with escape sequences replaced by their
     * equivalent character.
     */
public static String unescape(String escaped) {
    StringBuffer result = new StringBuffer(escaped.length());
    Matcher m = Pattern.compile("\\\\(?:([a-fA-F0-9]{2,6})|(.))").matcher(escaped);
    while (m.find()) {
        if (m.group(1) != null)
            m.appendReplacement(result, String.valueOf((char) Integer.parseInt(m.group(1), 16)));
        else if (m.group(2) != null)
            m.appendReplacement(result, m.group(2));
    }
    m.appendTail(result);
    return result.toString();
}

52. HTMLFilter#checkTags()

Project: blade
Source File: HTMLFilter.java
View license
private String checkTags(String s) {
    Matcher m = P_TAGS.matcher(s);
    final StringBuffer buf = new StringBuffer();
    while (m.find()) {
        String replaceStr = m.group(1);
        replaceStr = processTag(replaceStr);
        m.appendReplacement(buf, Matcher.quoteReplacement(replaceStr));
    }
    m.appendTail(buf);
    s = buf.toString();
    // (remember to reset before subsequent calls to filter method)
    for (String key : vTagCounts.keySet()) {
        for (int ii = 0; ii < vTagCounts.get(key); ii++) {
            s += "</" + key + ">";
        }
    }
    return s;
}

53. HTMLFilter#validateEntities()

Project: blade
Source File: HTMLFilter.java
View license
private String validateEntities(final String s) {
    StringBuffer buf = new StringBuffer();
    // validate entities throughout the string
    Matcher m = P_VALID_ENTITIES.matcher(s);
    while (m.find()) {
        //([^&;]*)
        final String one = m.group(1);
        //(?=(;|&|$))
        final String two = m.group(2);
        m.appendReplacement(buf, Matcher.quoteReplacement(checkEntity(one, two)));
    }
    m.appendTail(buf);
    return encodeQuotes(buf.toString());
}

54. SailGraphSpecificTestSuite#testLiterals()

View license
public void testLiterals() {
    assertTrue(SailHelper.isLiteral("\"java\"^^<http://www.w3.org/2001/XMLSchema#string>"));
    assertFalse(SailHelper.isLiteral("http://www.w3.org/2001/XMLSchema#string"));
    assertFalse(SailHelper.isLiteral("^^<http://www.w3.org/2001/XMLSchema#string>"));
    assertTrue(SailHelper.isLiteral("\"\"^^<http://www.w3.org/2001/XMLSchema#string>"));
    assertTrue(SailHelper.isLiteral("\"\""));
    assertTrue(SailHelper.isLiteral("\"marko\""));
    assertFalse(SailHelper.isLiteral("\"marko\"marko"));
    assertFalse(SailHelper.isLiteral("\""));
    // TODO: make this true assertFalse(SesameGraph.isLiteral("\"marko\"marko\""));
    Matcher matcher = SailHelper.literalPattern.matcher("\"java\"^^<http://www.w3.org/2001/XMLSchema#string>");
    matcher.matches();
    assertNull(matcher.group(6));
    assertEquals(matcher.group(1), "java");
    assertEquals(matcher.group(4), "http://www.w3.org/2001/XMLSchema#string");
    matcher = SailHelper.literalPattern.matcher("\"java\"@en");
    matcher.matches();
    assertNull(matcher.group(4));
    assertEquals(matcher.group(1), "java");
    assertEquals(matcher.group(6), "en");
}

55. SourceFS#transform()

Project: bnd
Source File: SourceFS.java
View license
public String transform(String s) throws Exception {
    Matcher m = LOCAL_P.matcher(s);
    StringBuffer sb = new StringBuffer();
    boolean found = false;
    while (m.find()) {
        FileDescription fd = toRemote(m.group(0));
        fd.touched = true;
        m.appendReplacement(sb, fd.path);
        found = true;
    }
    if (!found)
        return s;
    m.appendTail(sb);
    return sb.toString();
}

56. OCDReader#fixup()

Project: bnd
Source File: OCDReader.java
View license
static String fixup(String name) {
    Matcher m = p.matcher(name);
    StringBuffer b = new StringBuffer();
    while (m.find()) {
        String // null;
        replacement = // null;
        "";
        if (m.group(1) != null)
            replacement = "\\$";
        if (m.group(2) != null)
            replacement = "";
        if (m.group(3) != null)
            replacement = "_";
        if (m.group(4) != null)
            replacement = ".";
        m.appendReplacement(b, replacement);
    }
    m.appendTail(b);
    return b.toString();
}

57. TaggedData#cleanHtml()

Project: bnd
Source File: TaggedData.java
View license
private String cleanHtml(CharSequence sb) {
    sb = HTML_TAGS_P.matcher(sb).replaceAll("");
    sb = NEWLINES_P.matcher(sb).replaceAll("\n");
    StringBuffer x = new StringBuffer();
    Matcher m = ENTITIES_P.matcher(sb);
    while (m.find()) {
        if (m.group("nr") != null) {
            char c = (char) Integer.parseInt(m.group("nr"));
            m.appendReplacement(x, "");
            x.append(c);
        } else {
            m.appendReplacement(x, entity(m.group("name")));
        }
    }
    m.appendTail(x);
    return x.toString();
}

58. POM#replaceMacros()

Project: bnd
Source File: POM.java
View license
private String replaceMacros(String value) {
    Matcher m = MACRO_P.matcher(value);
    StringBuffer sb = new StringBuffer();
    while (m.find()) {
        String key = m.group("key");
        if (m.group("env") != null)
            m.appendReplacement(sb, replaceMacros(System.getenv(key)));
        else {
            String property = this.properties.getProperty(key);
            if (property != null && property.indexOf('$') >= 0)
                property = replaceMacros(property);
            if (property == null) {
                System.out.println("?? prop: " + key);
                m.appendReplacement(sb, "\\$\\{" + key + "\\}");
            } else
                m.appendReplacement(sb, property);
        }
    }
    m.appendTail(sb);
    return sb.toString();
}

59. ReplaceManifestPlaceholdersStep#replacePlaceholders()

View license
@VisibleForTesting
static String replacePlaceholders(String content, ImmutableMap<String, String> placeholders) {
    Iterable<String> escaped = Iterables.transform(placeholders.keySet(), new Function<String, String>() {

        @Override
        public String apply(String input) {
            return Pattern.quote(input);
        }
    });
    Joiner joiner = Joiner.on("|");
    String patternString = Pattern.quote("${") + "(" + joiner.join(escaped) + ")" + Pattern.quote("}");
    Pattern pattern = Pattern.compile(patternString);
    Matcher matcher = pattern.matcher(content);
    StringBuffer sb = new StringBuffer();
    while (matcher.find()) {
        matcher.appendReplacement(sb, placeholders.get(matcher.group(1)));
    }
    matcher.appendTail(sb);
    return sb.toString();
}

60. DefaultMessageInterpolator#replaceVariables()

View license
private String replaceVariables(String message, ResourceBundle bundle, Locale locale, boolean recurse) {
    Matcher matcher = messageParameterPattern.matcher(message);
    StringBuffer sb = new StringBuffer(64);
    String resolvedParameterValue;
    while (matcher.find()) {
        String parameter = matcher.group(1);
        resolvedParameterValue = resolveParameter(parameter, bundle, locale, recurse);
        matcher.appendReplacement(sb, sanitizeForAppendReplacement(resolvedParameterValue));
    }
    matcher.appendTail(sb);
    return sb.toString();
}

61. DefaultMessageInterpolator#replaceAnnotationAttributes()

View license
private String replaceAnnotationAttributes(String message, Map<String, Object> annotationParameters) {
    Matcher matcher = messageParameterPattern.matcher(message);
    StringBuffer sb = new StringBuffer(64);
    while (matcher.find()) {
        String resolvedParameterValue;
        String parameter = matcher.group(1);
        Object variable = annotationParameters.get(removeCurlyBrace(parameter));
        if (variable != null) {
            if (variable.getClass().isArray()) {
                resolvedParameterValue = ArrayUtils.toString(variable);
            } else {
                resolvedParameterValue = variable.toString();
            }
        } else {
            resolvedParameterValue = parameter;
        }
        matcher.appendReplacement(sb, sanitizeForAppendReplacement(resolvedParameterValue));
    }
    matcher.appendTail(sb);
    return sb.toString();
}

62. ParserBase#decodeIdentifier()

Project: caja
Source File: ParserBase.java
View license
/**
   * Decodes escapes in an identifier to their literal codepoints so that
   * identifiers can be compared for equality via string equality of their
   * values.
   */
public static String decodeIdentifier(String identifier) {
    // 6 of those.
    if (identifier.indexOf('\\') < 0) {
        return identifier;
    }
    StringBuffer sb = new StringBuffer();
    Matcher m = UNICODE_ESCAPE.matcher(identifier);
    while (m.find()) {
        m.appendReplacement(sb, "");
        sb.append((char) Integer.parseInt(m.group(1), 16));
    }
    m.appendTail(sb);
    return sb.toString();
}

63. Capsule#expand()

Project: capsule
Source File: Capsule.java
View license
private String expand(String str) {
    if (str == null)
        return null;
    final StringBuffer sb = new StringBuffer();
    final Matcher m = PAT_VAR.matcher(str);
    while (m.find()) m.appendReplacement(sb, Matcher.quoteReplacement(getVarValue(xor(m.group(1), m.group(2)))));
    m.appendTail(sb);
    str = sb.toString();
    // str = expandCommandLinePath(str);
    return str;
}

64. DefaultResponse#sanitizeUrl()

Project: cas
Source File: DefaultResponse.java
View license
/**
     * Sanitize a URL provided by a relying party by normalizing non-printable
     * ASCII character sequences into spaces.  This functionality protects
     * against CRLF attacks and other similar attacks using invisible characters
     * that could be abused to trick user agents.
     *
     * @param  url  URL to sanitize.
     *
     * @return  Sanitized URL string.
     */
private static String sanitizeUrl(final String url) {
    final Matcher m = NON_PRINTABLE.matcher(url);
    final StringBuffer sb = new StringBuffer(url.length());
    boolean hasNonPrintable = false;
    while (m.find()) {
        m.appendReplacement(sb, " ");
        hasNonPrintable = true;
    }
    m.appendTail(sb);
    if (hasNonPrintable) {
        LOGGER.warn("The following redirect URL has been sanitized and may be sign of attack:\n{}", url);
    }
    return sb.toString();
}

65. X509SubjectPrincipalResolver#resolvePrincipalInternal()

View license
/**
     * Replaces placeholders in the descriptor with values extracted from attribute
     * values in relative distinguished name components of the DN.
     *
     * @param certificate X.509 certificate credential.
     * @return Resolved principal ID.
     * @see AbstractX509PrincipalResolver#resolvePrincipalInternal(java.security.cert.X509Certificate)
     */
@Override
protected String resolvePrincipalInternal(final X509Certificate certificate) {
    logger.debug("Resolving principal for {}", certificate);
    final StringBuffer sb = new StringBuffer();
    final Matcher m = ATTR_PATTERN.matcher(this.descriptor);
    final Map<String, AttributeContext> attrMap = new HashMap<>();
    final RDNSequence rdnSequence = new NameReader(certificate).readSubject();
    String name;
    String[] values;
    AttributeContext context;
    while (m.find()) {
        name = m.group(1);
        if (!attrMap.containsKey(name)) {
            values = getAttributeValues(rdnSequence, StandardAttributeType.fromName(name));
            attrMap.put(name, new AttributeContext(values));
        }
        context = attrMap.get(name);
        m.appendReplacement(sb, context.nextValue());
    }
    m.appendTail(sb);
    return sb.toString();
}

66. GdbInfoLine#parse()

Project: che
Source File: GdbInfoLine.java
View license
/**
     * Factory method.
     */
public static GdbInfoLine parse(GdbOutput gdbOutput) throws GdbParseException {
    String output = gdbOutput.getOutput();
    Matcher matcher = GDB_INFO_LINE.matcher(output);
    if (matcher.find()) {
        String lineNumber = matcher.group(1);
        String file = matcher.group(2);
        return new GdbInfoLine(new LocationImpl(file, Integer.parseInt(lineNumber)));
    }
    matcher = GDB_LINE_OUT_OF_RANGE.matcher(output);
    if (matcher.find()) {
        String lineNumber = matcher.group(1);
        String file = matcher.group(2);
        return new GdbInfoLine(new LocationImpl(file, Integer.parseInt(lineNumber)));
    }
    throw new GdbParseException(GdbInfoLine.class, output);
}

67. GdbInfoProgram#parse()

Project: che
Source File: GdbInfoProgram.java
View license
/**
     * Factory method.
     */
public static GdbInfoProgram parse(GdbOutput gdbOutput) throws GdbParseException {
    String output = gdbOutput.getOutput();
    Matcher matcher = GDB_PROGRAM_FINISHED.matcher(output);
    if (matcher.find()) {
        return new GdbInfoProgram(null);
    }
    matcher = GDB_PROGRAM_STOPPED.matcher(output);
    if (matcher.find()) {
        String address = matcher.group(1);
        return new GdbInfoProgram(address);
    }
    throw new GdbParseException(GdbInfoProgram.class, output);
}

68. ValidatePropertyValues#validateUnicodeRangeValue()

View license
/**
   * Verify that a unicode range value is legal.
   *
   *  <p>See <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/unicode-range"></a>.
   */
private void validateUnicodeRangeValue(CssUnicodeRangeNode value) {
    Matcher rangeMatcher = UNICODE_RANGE_PATTERN.matcher(value.getValue());
    Matcher wildcardMatcher = UNICODE_WILDCARD_PATTERN.matcher(value.getValue());
    if (!rangeMatcher.matches() && !wildcardMatcher.matches()) {
        reportError(UNICODE_RANGE_ERROR, value);
        return;
    }
    if (rangeMatcher.matches()) {
        for (int i = 1; i <= rangeMatcher.groupCount(); ++i) {
            validateSingleCodePoint(rangeMatcher.group(i), value);
        }
    } else {
        // wildcardMatcher.matches() == true.
        // The second group contains only question marks (?). We concatenate it as zeros to the number
        // prefix for purpose of validation.
        String codePoint = wildcardMatcher.group(1) + wildcardMatcher.group(2).replaceAll("\\?", "0");
        validateSingleCodePoint(codePoint, value);
    }
}

69. IcuSyntaxUtils#icuEscape()

View license
/**
   * Escapes ICU syntax characters in raw text.
   * @param rawText The raw text to escaped.
   * @return The escaped raw text. If the given raw text doesn't need escaping, then the same string
   *     object is returned.
   */
@VisibleForTesting
static String icuEscape(String rawText) {
    Matcher matcher = ICU_SYNTAX_CHAR_NEEDING_ESCAPE_PATTERN.matcher(rawText);
    if (!matcher.find()) {
        return rawText;
    }
    StringBuffer escapedTextSb = new StringBuffer();
    do {
        String repl = ICU_SYNTAX_CHAR_ESCAPE_MAP.get(matcher.group());
        matcher.appendReplacement(escapedTextSb, repl);
    } while (matcher.find());
    matcher.appendTail(escapedTextSb);
    return escapedTextSb.toString();
}

70. RawTextNode#toSourceString()

Project: closure-templates
Source File: RawTextNode.java
View license
@Override
public String toSourceString() {
    StringBuffer sb = new StringBuffer();
    // Must escape special chars to create valid source text.
    Matcher matcher = SPECIAL_CHARS_TO_ESCAPE.matcher(rawText);
    while (matcher.find()) {
        String specialCharTag = SPECIAL_CHAR_TO_TAG.get(matcher.group());
        matcher.appendReplacement(sb, Matcher.quoteReplacement(specialCharTag));
    }
    matcher.appendTail(sb);
    return sb.toString();
}

71. VMOptions#replace()

Project: consulo
Source File: VMOptions.java
View license
private static String replace(Pattern pattern, String text, String replacement, String prefix, String suffix, String defaultResult) {
    Matcher m = pattern.matcher(text);
    if (!m.find())
        return defaultResult;
    StringBuffer b = new StringBuffer();
    m.appendReplacement(b, prefix + Matcher.quoteReplacement(replacement) + suffix);
    m.appendTail(b);
    return b.toString();
}

72. StringUtil#formatLinks()

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

73. StringUtil#replaceUnicodeEscapeSequences()

Project: consulo
Source File: StringUtil.java
View license
public static String replaceUnicodeEscapeSequences(String text) {
    if (text == null)
        return null;
    final Matcher matcher = UNICODE_CHAR.matcher(text);
    if (!matcher.find())
        return text;
    matcher.reset();
    int lastEnd = 0;
    final StringBuilder sb = new StringBuilder(text.length());
    while (matcher.find()) {
        sb.append(text.substring(lastEnd, matcher.start()));
        final char c = (char) Integer.parseInt(matcher.group().substring(2), 16);
        sb.append(c);
        lastEnd = matcher.end();
    }
    sb.append(text.substring(lastEnd, text.length()));
    return sb.toString();
}

74. StringUtils#resolveVars()

Project: CoreNLP
Source File: StringUtils.java
View license
public static String resolveVars(String str, Map props) {
    if (str == null)
        return null;
    Pattern p = Pattern.compile("\\$\\{(\\w+)\\}");
    Matcher m = p.matcher(str);
    StringBuffer sb = new StringBuffer();
    while (m.find()) {
        String varName = null == m.group(1) ? m.group(2) : m.group(1);
        String vrValue;
        if (props.containsKey(varName)) {
            vrValue = ((String) props.get(varName));
        } else {
            vrValue = System.getenv(varName);
        }
        m.appendReplacement(sb, null == vrValue ? "" : vrValue);
    }
    m.appendTail(sb);
    return sb.toString();
}

75. SnippetGenerator#withNamedGroups()

Project: cucumber-jvm
Source File: SnippetGenerator.java
View license
private String withNamedGroups(String snippetPattern) {
    Matcher m = GROUP_PATTERN.matcher(snippetPattern);
    StringBuffer sb = new StringBuffer();
    int n = 1;
    while (m.find()) {
        m.appendReplacement(sb, "(" + snippet.namedGroupStart() + n++ + snippet.namedGroupEnd());
    }
    m.appendTail(sb);
    return sb.toString();
}

76. DCMTools#substitude()

Project: DataCenterManager
Source File: DCMTools.java
View license
public static String substitude(String text, String regex) {
    //String text = "Hallo, hij zei: \"geef mijn 'pen' terug.\", dus; dat deed ik.";
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(text);
    StringBuffer newtext = new StringBuffer();
    while (matcher.find()) {
        matcher.appendReplacement(newtext, "");
    }
    matcher.appendTail(newtext);
    return newtext.toString();
}

77. DCMTools#split()

Project: DataCenterManager
Source File: DCMTools.java
View license
public static String split(String text, String separator) {
    //String text = "Hallo, hij zei: \"geef mijn 'pen' terug.\", dus; dat deed ik.";
    Pattern pattern = Pattern.compile(separator);
    Matcher matcher = pattern.matcher(text);
    StringBuffer newtext = new StringBuffer();
    while (matcher.find()) {
        matcher.appendReplacement(newtext, "");
    }
    matcher.appendTail(newtext);
    return newtext.toString();
}

78. IOChannelUtils#constructName()

Project: DataflowJavaSDK
Source File: IOChannelUtils.java
View license
/**
   * Constructs a fully qualified name from components.
   *
   * <p>The name is built from a prefix, shard template (with shard numbers
   * applied), and a suffix.  All components are required, but may be empty
   * strings.
   *
   * <p>Within a shard template, repeating sequences of the letters "S" or "N"
   * are replaced with the shard number, or number of shards respectively.  The
   * numbers are formatted with leading zeros to match the length of the
   * repeated sequence of letters.
   *
   * <p>For example, if prefix = "output", shardTemplate = "-SSS-of-NNN", and
   * suffix = ".txt", with shardNum = 1 and numShards = 100, the following is
   * produced:  "output-001-of-100.txt".
   */
public static String constructName(String prefix, String shardTemplate, String suffix, int shardNum, int numShards) {
    // Matcher API works with StringBuffer, rather than StringBuilder.
    StringBuffer sb = new StringBuffer();
    sb.append(prefix);
    Matcher m = SHARD_FORMAT_RE.matcher(shardTemplate);
    while (m.find()) {
        boolean isShardNum = (m.group(1).charAt(0) == 'S');
        char[] zeros = new char[m.end() - m.start()];
        Arrays.fill(zeros, '0');
        DecimalFormat df = new DecimalFormat(String.valueOf(zeros));
        String formatted = df.format(isShardNum ? shardNum : numShards);
        m.appendReplacement(sb, formatted);
    }
    m.appendTail(sb);
    sb.append(suffix);
    return sb.toString();
}

79. ParseUtils#interpolate()

Project: dubbo
Source File: ParseUtils.java
View license
/**
     * ??interpolation(????)?
     * 
     * @param expression ????????????????????????<code>{}</code>????
     * @param params ???????????<code>.</code>?<code>_</code>???
     * @return ??interpolation?????? ??<code><pre>xxx${name}zzz -> xxxjerryzzz</pre></code>?????name="jerry"?
     * @throws IllegalStateException ????????????? ???????
     */
// FIMXE ??IllegalStateException?????????
public static String interpolate(String expression, Map<String, String> params) {
    if (expression == null || expression.length() == 0) {
        throw new IllegalArgumentException("glob pattern is empty!");
    }
    if (expression.indexOf('$') < 0) {
        return expression;
    }
    Matcher matcher = VARIABLE_PATTERN.matcher(expression);
    StringBuffer sb = new StringBuffer();
    while (matcher.find()) {
        // ????
        String key = matcher.group(1);
        String value = params == null ? null : params.get(key);
        if (value == null) {
            value = "";
        }
        matcher.appendReplacement(sb, value);
    }
    matcher.appendTail(sb);
    return sb.toString();
}

80. ParseUtils#replaceParameter()

Project: dubbo
Source File: ParseUtils.java
View license
/**
     * ??url??????
     */
public static String replaceParameter(String query, String key, String value) {
    if (query == null || query.length() == 0) {
        return key + "=" + value;
    }
    if (query.indexOf(key + "=") == -1) {
        return query + "&" + key + "=" + value;
    }
    Pattern pattern = REPLACE_PARAMETER_PATTERNS.get(key);
    if (pattern == null) {
        pattern = Pattern.compile(key.replaceAll("([^(_0-9A-Za-z)])", "\\\\$0") + "=[^&]+");
    }
    Matcher matcher = pattern.matcher(query);
    StringBuffer sb = new StringBuffer();
    while (matcher.find()) {
        matcher.appendReplacement(sb, (key + "=" + value).replace("$", "\\$"));
    }
    matcher.appendTail(sb);
    return sb.toString();
}

81. ConfigUtils#replaceProperty()

Project: dubbo
Source File: ConfigUtils.java
View license
public static String replaceProperty(String expression, Map<String, String> params) {
    if (expression == null || expression.length() == 0 || expression.indexOf('$') < 0) {
        return expression;
    }
    Matcher matcher = VARIABLE_PATTERN.matcher(expression);
    StringBuffer sb = new StringBuffer();
    while (matcher.find()) {
        // ????
        String key = matcher.group(1);
        String value = System.getProperty(key);
        if (value == null && params != null) {
            value = params.get(key);
        }
        if (value == null) {
            value = "";
        }
        matcher.appendReplacement(sb, Matcher.quoteReplacement(value));
    }
    matcher.appendTail(sb);
    return sb.toString();
}

82. GalleryListParser#parseRating()

Project: EhViewer
Source File: GalleryListParser.java
View license
private static String parseRating(String ratingStyle) {
    Matcher m = PATTERN_RATING.matcher(ratingStyle);
    int num1;
    int num2;
    int rate = 5;
    String re;
    if (m.find()) {
        num1 = ParserUtils.parseInt(m.group().replace("px", ""));
    } else {
        return null;
    }
    if (m.find()) {
        num2 = ParserUtils.parseInt(m.group().replace("px", ""));
    } else {
        return null;
    }
    rate = rate - num1 / 16;
    if (num2 == 21) {
        rate--;
        re = Integer.toString(rate);
        re = re + ".5";
    } else
        re = Integer.toString(rate);
    return re;
}

83. Augmentation#replaceAll()

Project: elasticsearch
Source File: Augmentation.java
View license
// CharSequence augmentation
/**
     * Replace all matches. Similar to [email protected] Matcher#replaceAll(String)} but allows you to customize the replacement based on the match.
     */
public static String replaceAll(CharSequence receiver, Pattern pattern, Function<Matcher, String> replacementBuilder) {
    Matcher m = pattern.matcher(receiver);
    if (false == m.find()) {
        // CharSequqence's toString is *supposed* to always return the characters in the sequence as a String
        return receiver.toString();
    }
    StringBuffer result = new StringBuffer(initialBufferForReplaceWith(receiver));
    do {
        m.appendReplacement(result, Matcher.quoteReplacement(replacementBuilder.apply(m)));
    } while (m.find());
    m.appendTail(result);
    return result.toString();
}

84. TestSearchPaths#getURIFromSource()

View license
private static URI getURIFromSource(String source) {
    String packageName = null;
    Matcher matcher = packagePattern.matcher(source);
    if (matcher.find()) {
        packageName = matcher.group(1).replace(".", "/");
    }
    matcher = classPattern.matcher(source);
    if (matcher.find()) {
        String className = matcher.group(1);
        String path = ((packageName == null) ? "" : packageName + "/") + className + ".java";
        return URI.create("myfo:///" + path);
    } else {
        throw new Error("Could not extract the java class " + "name from the provided source");
    }
}

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

86. AbstractScriptLanguageMgmt#getExpressionAll()

View license
public static String getExpressionAll(String inexp) {
    String str = null;
    String regex = __REGEX_SIGNS;
    Pattern regexExpType = Pattern.compile(regex);
    Matcher mType = regexExpType.matcher(inexp);
    String expType = inexp;
    StringBuffer sb = new StringBuffer();
    while (mType.find()) {
        expType = mType.group();
        // StringUtil.getString(getExpressionValue(dataView,expType));
        String dist = expType.substring(2, expType.length() - 1);
        mType.appendReplacement(sb, dist);
    }
    mType.appendTail(sb);
    str = sb.toString();
    return str;
}

87. MyTest#getExpressionAll()

Project: fixflow
Source File: MyTest.java
View license
public static String getExpressionAll(String inexp) {
    String str = null;
    String regex = __REGEX_SIGNS;
    Pattern regexExpType = Pattern.compile(regex);
    Matcher mType = regexExpType.matcher(inexp);
    String expType = inexp;
    StringBuffer sb = new StringBuffer();
    while (mType.find()) {
        expType = mType.group();
        String dist = expType.substring(2, expType.length() - 1);
        // StringUtil.getString(getExpressionValue(dataView,expType));
        mType.appendReplacement(sb, dist);
    }
    mType.appendTail(sb);
    str = sb.toString();
    return str;
}

88. EntityProcessor#convertEntity()

Project: flex-falcon
Source File: EntityProcessor.java
View license
private static int convertEntity(String entityName, MXMLDialect mxmlDialect) {
    Character ch = mxmlDialect.getNamedEntity(entityName);
    if (ch != null)
        return ch.charValue();
    // TODO What happens with Unicode characters
    // outside the BMP, such as 𒍅 ?
    Matcher m = HEX_PATTERN.matcher(entityName);
    if (m.matches())
        return Integer.parseInt(m.group(1), 16);
    m = DECIMAL_PATTERN.matcher(entityName);
    if (m.matches())
        return Integer.parseInt(m.group(1));
    return -1;
}

89. RemapSources#replaceInLine()

Project: ForgeGradle
Source File: RemapSources.java
View license
private String replaceInLine(String line) {
    // FAR all methods
    StringBuffer buf = new StringBuffer();
    Matcher matcher = SRG_FINDER.matcher(line);
    while (matcher.find()) {
        String find = matcher.group(1);
        if (find.startsWith("p_"))
            find = params.get(find);
        else if (find.startsWith("func_"))
            find = methods.get(find);
        else if (find.startsWith("field_"))
            find = fields.get(find);
        if (find == null)
            find = matcher.group(1);
        matcher.appendReplacement(buf, find);
        buf.append(matcher.group(2));
    }
    matcher.appendTail(buf);
    return buf.toString();
}

90. RequestMappingTest#testRegex()

Project: Gaea
Source File: RequestMappingTest.java
View license
@Test
public void testRegex() {
    String regUrl = "/news/(\\d+)";
    String sourceUrl = "/news/101001";
    Pattern pattern = Pattern.compile(regUrl);
    Matcher matcher = pattern.matcher(sourceUrl);
    if (matcher.find()) {
        Assert.assertEquals("101001", matcher.group(1));
    }
    regUrl = "/news/(\\d+)/(\\w+)/(\\d+)";
    sourceUrl = "/news/101002/abc123/23456";
    pattern = Pattern.compile(regUrl);
    matcher = pattern.matcher(sourceUrl);
    if (matcher.find()) {
        Assert.assertEquals("101002", matcher.group(1));
        Assert.assertEquals("abc123", matcher.group(2));
        Assert.assertEquals("23456", matcher.group(3));
    }
}

91. UrlMatcher#replaceRegexs()

Project: gecco
Source File: UrlMatcher.java
View license
public static String replaceRegexs(String srcUrl, String regex, Map<String, String> params) {
    if (params == null) {
        return srcUrl;
    }
    StringBuffer sb = new StringBuffer();
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(srcUrl);
    while (matcher.find()) {
        String name = matcher.group(1);
        String value = params.get(name);
        if (StringUtils.isNotEmpty(value)) {
            matcher.appendReplacement(sb, value);
        }
    }
    matcher.appendTail(sb);
    return sb.toString();
}

92. HtmlUtils#rewriteRelativeUrls()

Project: gh4a
Source File: HtmlUtils.java
View license
/**
     * Rewrite relative URLs in HTML fetched e.g. from markdown files.
     *
     * @param html
     * @param repoUser
     * @param repoName
     * @param branch
     * @return
     */
public static String rewriteRelativeUrls(final String html, final String repoUser, final String repoName, final String branch) {
    final String baseUrl = "https://raw.github.com/" + repoUser + "/" + repoName + "/" + branch;
    final StringBuffer sb = new StringBuffer();
    final Pattern p = Pattern.compile("(href|src)=\"(\\S+)\"");
    final Matcher m = p.matcher(html);
    while (m.find()) {
        String url = m.group(2);
        if (!url.contains("://") && !url.startsWith("#")) {
            if (url.startsWith("/")) {
                url = baseUrl + url;
            } else {
                url = baseUrl + "/" + url;
            }
        }
        m.appendReplacement(sb, Matcher.quoteReplacement(m.group(1) + "=\"" + url + "\""));
    }
    m.appendTail(sb);
    return sb.toString();
}

93. HtmlUtils#rewriteRelativeUrls()

Project: Gitskarios
Source File: HtmlUtils.java
View license
/**
   * Rewrite relative URLs in HTML fetched e.g. from markdown files.
   */
public static String rewriteRelativeUrls(final String html, final String repoUser, final String repoName, final String branch) {
    final String baseUrl = "https://raw.github.com/" + repoUser + "/" + repoName + "/" + branch;
    final StringBuffer sb = new StringBuffer();
    final Pattern p = Pattern.compile("(href|src)=\"(\\S+)\"");
    final Matcher m = p.matcher(html);
    while (m.find()) {
        String url = m.group(2);
        if (!url.contains("://") && !url.startsWith("#")) {
            if (url.startsWith("/")) {
                url = baseUrl + url;
            } else {
                url = baseUrl + "/" + url;
            }
        }
        m.appendReplacement(sb, Matcher.quoteReplacement(m.group(1) + "=\"" + url + "\""));
    }
    m.appendTail(sb);
    return sb.toString();
}

94. 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;
}

95. GraphManager#GetTemplate()

Project: graphify
Source File: GraphManager.java
View license
/**
     * Gets a template representation of a RegEx string, making it easier to read a text pattern.
     * @param pattern The RegEx string to translate into a readable string template.
     * @return Returns a readable format of the RegEx, with {n} in place of wildcard matches.
     */
public String GetTemplate(String pattern) {
    Pattern generalMatcher = Pattern.compile(WILDCARD_TEMPLATE);
    Matcher regexMatcher = generalMatcher.matcher(pattern);
    StringBuffer s = new StringBuffer();
    int counter = 0;
    while (regexMatcher.find()) {
        regexMatcher.appendReplacement(s, "{" + counter + "}");
        counter++;
    }
    regexMatcher.appendTail(s);
    return s.toString().replace("\\[\\s\\]", " ").replace("\\s?", " ").replace("\\s", " ");
}

96. GraphManager#GeneratePattern()

Project: graphify
Source File: GraphManager.java
View license
/**
     * Generates a child pattern from a supplied parent pattern.
     * @param patternCount A vector of words containing sorted on frequency of matches from historic data.
     * @return Returns a new child pattern that is generated from the patternCount model.
     */
public String GeneratePattern(PatternCount patternCount) {
    Pattern generalMatcher = Pattern.compile(WILDCARD_TEMPLATE);
    Matcher regexMatcher = generalMatcher.matcher(GraphManager.ROOT_TEMPLATE);
    StringBuffer s = new StringBuffer();
    int counter = 0;
    while (regexMatcher.find()) {
        if (counter == 0) {
            StringBuilder sb = new StringBuilder();
            sb.append(WILDCARD_TEMPLATE);
            regexMatcher.appendReplacement(s, (sb.toString() + ("\\\\s" + patternCount.getPattern())));
        } else {
            regexMatcher.appendReplacement(s, regexMatcher.group().replace("\\", "\\\\"));
        }
        counter++;
    }
    regexMatcher.appendTail(s);
    return s.toString();
}

97. LearningManager#GetTemplate()

Project: graphify
Source File: LearningManager.java
View license
/**
     * Gets a template representation of a RegEx string, making it easier to read a text pattern.
     * @param pattern The RegEx string to translate into a readable string template.
     * @return Returns a readable format of the RegEx, with {n} in place of wildcard matches.
     */
private static String GetTemplate(String pattern) {
    Pattern generalMatcher = Pattern.compile(GraphManager.WILDCARD_TEMPLATE);
    Matcher regexMatcher = generalMatcher.matcher(pattern);
    StringBuffer s = new StringBuffer();
    int counter = 0;
    while (regexMatcher.find()) {
        regexMatcher.appendReplacement(s, "{" + counter + "}");
        counter++;
    }
    regexMatcher.appendTail(s);
    return s.toString().replace("\\[\\s\\]", " ").replace("\\s?", " ").replace("\\s", " ");
}

98. LearningManager#GeneratePattern()

Project: graphify
Source File: LearningManager.java
View license
/**
     * Generates a child pattern from a supplied parent pattern.
     * @param i The index of the wildcard word within the parent RegEx pattern.
     * @param patternCount A vector of words containing sorted on frequency of matches from historic data.
     * @param pattern The RegEx string of the parent pattern.
     * @return Returns a new child pattern that is generated from the patternCount model.
     */
private static String GeneratePattern(int i, PatternCount patternCount, String pattern) {
    Pattern generalMatcher = Pattern.compile(GraphManager.WILDCARD_TEMPLATE);
    Matcher regexMatcher = generalMatcher.matcher(pattern);
    StringBuffer s = new StringBuffer();
    int counter = 0;
    while (regexMatcher.find()) {
        if (counter == i) {
            StringBuilder sb = new StringBuilder();
            sb.append(GraphManager.WILDCARD_TEMPLATE);
            regexMatcher.appendReplacement(s, ((counter == 0) ? sb.toString() + ("\\\\s" + patternCount.getPattern()) : (patternCount.getPattern() + "\\\\s") + sb.toString()));
        } else {
            regexMatcher.appendReplacement(s, regexMatcher.group().replace("\\", "\\\\"));
        }
        counter++;
    }
    regexMatcher.appendTail(s);
    return s.toString();
}

99. Inflector#replaceAllWithUppercase()

Project: hapi-fhir
Source File: Inflector.java
View license
/**
     * Utility method to replace all occurrences given by the specific backreference with its uppercased form, and remove all
     * other backreferences.
     * 
     * The Java [email protected] 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();
}

100. Inflector#replaceAllWithUppercase()

Project: hapi-fhir
Source File: Inflector.java
View license
/**
     * Utility method to replace all occurrences given by the specific backreference with its uppercased form, and remove all
     * other backreferences.
     * 
     * The Java [email protected] 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();
}