Java Code Examples for java.util.regex.MatchResult

The following are top voted examples for showing how to use java.util.regex.MatchResult. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: jdk8u-jdk   File: TzdbZoneRulesCompiler.java   Source Code and License 7 votes vote down vote up
private int parseYear(Scanner s, int defaultYear) {
    if (s.hasNext(YEAR)) {
        s.next(YEAR);
        MatchResult mr = s.match();
        if (mr.group(1) != null) {
            return 1900;  // systemv has min
        } else if (mr.group(2) != null) {
            return YEAR_MAX_VALUE;
        } else if (mr.group(3) != null) {
            return defaultYear;
        }
        return Integer.parseInt(mr.group(4));
        /*
        if (mr.group("min") != null) {
            //return YEAR_MIN_VALUE;
            return 1900;  // systemv has min
        } else if (mr.group("max") != null) {
            return YEAR_MAX_VALUE;
        } else if (mr.group("only") != null) {
            return defaultYear;
        }
        return Integer.parseInt(mr.group("year"));
        */
    }
    throw new IllegalArgumentException("Unknown year: " + s.next());
}
 
Example 2
Project: openjdk-jdk10   File: DefaultFormat.java   Source Code and License 7 votes vote down vote up
protected ThreadStack parseThreadInfo(String threadInfo) {
    Scanner s = new Scanner(threadInfo);
    ThreadStack result = new ThreadStack();

    // parsing thread info
    s.findInLine(threadInfoPattern());
    MatchResult res = s.match();

    result.setThreadName(res.group(1));

    result.setType(res.group(3));

    result.setPriority(res.group(4));
    result.setTid(res.group(7));
    result.setNid(res.group(8));
    result.setStatus(res.group(9));

    s.close();
    return result;
}
 
Example 3
Project: openjdk-jdk10   File: DefaultFormat.java   Source Code and License 7 votes vote down vote up
protected MethodInfo parseMethodInfo(String line) {

        MethodInfo result = new MethodInfo();
        Scanner s = new Scanner(line);

        s.findInLine(methodInfoPattern());
        MatchResult rexp = s.match();
        if (rexp.group(4) != null && rexp.group(4).length() > 0) {
            // line "  at tmtools.jstack.share.utils.Utils.sleep(Utils.java:29)"
            result.setName(rexp.group(1));
            result.setCompilationUnit(rexp.group(2));
            result.setLine(rexp.group(4));

        } else {
            // line "  at java.lang.Thread.sleep(Native Method)"
            result.setName(rexp.group(1));
        }

        s.close();
        return result;
    }
 
Example 4
Project: openddr-java   File: WinCEMozillaSubBuilder.java   Source Code and License 7 votes vote down vote up
private void setWinCeVersion(OperatingSystem model) {
    //TODO: to be refined
    String osV = model.getVersion();
    if (osV == null) {
        return;

    } else if (!model.getMajorRevision().equals("1")) {
        return;
    }

    if (osV.matches(".*(\\d+).(\\d+).(\\d+).(\\d+).*")) {
        Scanner s = new Scanner(osV);
        s.findInLine(".*(\\d+).(\\d+).(\\d+).(\\d+).*");
        MatchResult result = s.match();
        if (result.group(1).equals("4")) {
            model.setMajorRevision("5");

        } else if (result.group(1).equals("6")) {
            model.setMajorRevision("6");

            if (result.group(3).equals("7")) {
                model.setMinorRevision("1");
            }
        }
    }
}
 
Example 5
Project: Wurst-MC-1.12   File: JGoogleAnalyticsTracker.java   Source Code and License 6 votes vote down vote up
/**
 * Define the proxy to use for all GA tracking requests.
 * <p>
 * Call this static method early (before creating any tracking requests).
 *
 * @param proxyAddr
 *            "addr:port" of the proxy to use; may also be given as URL
 *            ("http://addr:port/").
 */
public static void setProxy(String proxyAddr)
{
	if(proxyAddr != null)
	{
		Scanner s = new Scanner(proxyAddr);
		
		// Split into "proxyAddr:proxyPort".
		proxyAddr = null;
		int proxyPort = 8080;
		try
		{
			s.findInLine("(http://|)([^:/]+)(:|)([0-9]*)(/|)");
			MatchResult m = s.match();
			
			if(m.groupCount() >= 2)
				proxyAddr = m.group(2);
			
			if(m.groupCount() >= 4 && !(m.group(4).length() == 0))
				proxyPort = Integer.parseInt(m.group(4));
		}finally
		{
			s.close();
		}
		
		if(proxyAddr != null)
		{
			SocketAddress sa = new InetSocketAddress(proxyAddr, proxyPort);
			setProxy(new Proxy(Type.HTTP, sa));
		}
	}
}
 
Example 6
Project: springreplugin   File: DownloadFileInfo.java   Source Code and License 6 votes vote down vote up
/**
 * 根据文件名得到插件名
 *
 * @param fullname
 * @param type
 * @return
 */
public static final String parseName(String fullname, int type) {
    Matcher m = null;
    if (type == INCREMENT_PLUGIN) {
        m = INCREMENT_REGEX.matcher(fullname);
    } else if (type == SINGLE_PLUGIN) {
        m = INCREMENT_SINGLE_REGEX.matcher(fullname);
    } else if (type == MULTI_PLUGIN) {
        m = MULTI_REGEX.matcher(fullname);
    } else {
        m = NORMAL_REGEX.matcher(fullname);
    }
    if (m == null || !m.matches()) {
        return null;
    }
    MatchResult r = m.toMatchResult();
    if (r == null || r.groupCount() != 1) {
        return null;
    }
    return r.group(1);
}
 
Example 7
Project: openjdk-jdk10   File: DefaultFormat.java   Source Code and License 6 votes vote down vote up
private MonitorInfo parseMonitorInfo(String line, String pattern) {
    Scanner s = new Scanner(line);
    s.findInLine(pattern);
    MonitorInfo mi = new MonitorInfo();
    MatchResult res = s.match();

    mi.setType(res.group(1));
    mi.setMonitorAddress(res.group(2));
    if (res.groupCount() > 2) {
        mi.setMonitorClass(res.group(3));
    }
    return mi;
}
 
Example 8
Project: openjdk-jdk10   File: DefaultFormat.java   Source Code and License 6 votes vote down vote up
protected LockInfo parseLockInfo(String line) {
    LockInfo res = new LockInfo();

    Scanner s = new Scanner(line);
    s.findInLine(ownableSynchronizersPattern());

    MatchResult matchRes = s.match();
    String lock = matchRes.group(1).equals("None") ? matchRes.group(1) : matchRes.group(2);
    res.setLock(lock);

    return res;
}
 
Example 9
Project: openjdk-jdk10   File: ScannerStreamTest.java   Source Code and License 6 votes vote down vote up
public void findAllFileTest() {
    // derive expected result by using conventional loop
    Pattern pat = Pattern.compile("[A-Z]{7,}");
    List<String> expected = new ArrayList<>();

    try (Scanner sc = makeFileScanner(inputFile)) {
        String match;
        while ((match = sc.findWithinHorizon(pat, 0)) != null) {
            expected.add(match);
        }
    }

    Supplier<Stream<String>> ss =
        () -> makeFileScanner(inputFile).findAll(pat).map(MatchResult::group);

    withData(TestData.Factory.ofSupplier("findAllFileTest", ss))
            .stream(LambdaTestHelpers.identity())
            .expectedResult(expected)
            .exercise();
}
 
Example 10
Project: openjdk-jdk10   File: ScannerStreamTest.java   Source Code and License 6 votes vote down vote up
@Test(dataProvider = "FindAllZero")
public void findAllZeroTest(String input, String patternString) {
    Pattern pattern = Pattern.compile(patternString);

    // generate expected result using Matcher.find()
    Matcher m = pattern.matcher(input);
    List<String> expected = new ArrayList<>();
    while (m.find()) {
        expected.add(m.group());
    }

    Supplier<Stream<String>> ss = () -> new Scanner(input).findAll(pattern)
                                                          .limit(100)
                                                          .map(MatchResult::group);

    withData(TestData.Factory.ofSupplier("findAllZeroTest", ss))
            .stream(LambdaTestHelpers.identity())
            .expectedResult(expected)
            .exercise();
}
 
Example 11
Project: goobi-viewer-indexer   File: MetadataHelper.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) {
    String string = "Vol. 15 xxx";
    Pattern p = Pattern.compile(".*(\\d+).*");
    Matcher m = p.matcher(string);

    if (m.find()) {
        MatchResult mr = m.toMatchResult();
        String value = mr.group(1);
        System.out.println("found: " + value);
    }

    p = Pattern.compile("\\d+");
    m = p.matcher(string);
    while (m.find()) {
        try {
            String sub = string.substring(m.start(), m.end());
            System.out.println("found 2: " + sub);
        } catch (NumberFormatException e) {
            logger.error(e.getMessage());
        }
    }
}
 
Example 12
Project: skript-mirror   File: ExprParseRegex.java   Source Code and License 6 votes vote down vote up
@Override
protected String[] get(Event e) {
  List<MatchResult> regexes = ((CustomSyntaxEvent) e).getParseResult().regexes;
  if (index < regexes.size()) {
    MatchResult match = regexes.get(index);
    int groupCount = match.groupCount();
    String[] groups = new String[groupCount];

    for (int i = 1; i <= groupCount; i++) {
      groups[i - 1] = match.group(i);
    }

    return groups;
  }
  return new String[0];
}
 
Example 13
Project: temporize   File: TokenCreator.java   Source Code and License 6 votes vote down vote up
public static TokenCreator getCreator() {
    return new TokenCreator() {

        @Override
        public Pattern getPattern() {
            return EXP;
        }

        @Override
        public Token create(MatchResult matchResult, String source, int line) {
            return new Token.Variable(matchResult.group(),
                    matchResult.group(1), "|def" + matchResult.group(2),
                    source, line, matchResult.start());
        }
    };
}
 
Example 14
Project: CostFed   File: QueryManager.java   Source Code and License 6 votes vote down vote up
/**
 * Find all prefixes declared in the query
 * @param queryString
 * @return
 */
protected static Set<String> findQueryPrefixes(String queryString) {
	
	Set<String> res = new HashSet<String>();
	
	Scanner sc = new Scanner(queryString);
	while (true) {
		while (sc.findInLine(prefixPattern)!=null) {
			MatchResult m = sc.match();
			res.add(m.group(1));
		}
		if (!sc.hasNextLine())
			break;
		sc.nextLine();
	}
	sc.close();
	return res;
}
 
Example 15
Project: openjdk9   File: DefaultFormat.java   Source Code and License 6 votes vote down vote up
protected ThreadStack parseThreadInfo(String threadInfo) {
    Scanner s = new Scanner(threadInfo);
    ThreadStack result = new ThreadStack();

    // parsing thread info
    s.findInLine(threadInfoPattern());
    MatchResult res = s.match();

    result.setThreadName(res.group(1));

    result.setType(res.group(3));

    result.setPriority(res.group(4));
    result.setTid(res.group(7));
    result.setNid(res.group(8));
    result.setStatus(res.group(9));

    s.close();
    return result;
}
 
Example 16
Project: openjdk9   File: DefaultFormat.java   Source Code and License 6 votes vote down vote up
protected MethodInfo parseMethodInfo(String line) {

        MethodInfo result = new MethodInfo();
        Scanner s = new Scanner(line);

        s.findInLine(methodInfoPattern());
        MatchResult rexp = s.match();
        if (rexp.group(4) != null && rexp.group(4).length() > 0) {
            // line "  at tmtools.jstack.share.utils.Utils.sleep(Utils.java:29)"
            result.setName(rexp.group(1));
            result.setCompilationUnit(rexp.group(2));
            result.setLine(rexp.group(4));

        } else {
            // line "  at java.lang.Thread.sleep(Native Method)"
            result.setName(rexp.group(1));
        }

        s.close();
        return result;
    }
 
Example 17
Project: openjdk9   File: ScannerStreamTest.java   Source Code and License 6 votes vote down vote up
public void findAllTest() {
    // derive expected result by using conventional loop
    Pattern pat = Pattern.compile("[A-Z]{7,}");
    List<String> expected = new ArrayList<>();

    try (Scanner sc = makeFileScanner(inputFile)) {
        String match;
        while ((match = sc.findWithinHorizon(pat, 0)) != null) {
            expected.add(match);
        }
    }

    Supplier<Stream<String>> ss =
        () -> makeFileScanner(inputFile).findAll(pat).map(MatchResult::group);

    withData(TestData.Factory.ofSupplier("findAllTest", ss))
            .stream(LambdaTestHelpers.identity())
            .expectedResult(expected)
            .exercise();
}
 
Example 18
Project: RedisConnector   File: StringUtils.java   Source Code and License 6 votes vote down vote up
public static String substituteTemplate(final IContext context, String template,
		final IMendixObject substitute, final boolean HTMLEncode, final String datetimeformat) {
	return regexReplaceAll(template, "\\{(@)?([\\w./]+)\\}", new Function<MatchResult, String>() {

		@Override
		public String apply(MatchResult match)
		{
			String value;
			String path = match.group(2);
			if (match.group(1) != null)
				value = String.valueOf(Core.getConfiguration().getConstantValue(path));
			else {
				try
				{
					value = ORM.getValueOfPath(context, substitute, path,	datetimeformat);
				}
				catch (Exception e)
				{
					throw new RuntimeException(e);
				}
			}
			return HTMLEncode ? HTMLEncode(value) : value;
		}
		
	});
}
 
Example 19
Project: RedisConnector   File: StringUtils.java   Source Code and License 6 votes vote down vote up
public static String regexReplaceAll(String source, String regexString, Function<MatchResult, String> replaceFunction)  {
	if (source == null || source.trim().isEmpty()) // avoid NPE's, save CPU
		return "";

	StringBuffer resultString = new StringBuffer();
	Pattern regex = Pattern.compile(regexString);
	Matcher regexMatcher = regex.matcher(source);
	
	while (regexMatcher.find()) {
		MatchResult match = regexMatcher.toMatchResult();
		String value = replaceFunction.apply(match); 
		regexMatcher.appendReplacement(resultString, Matcher.quoteReplacement(value));
	}
	regexMatcher.appendTail(resultString);

	return resultString.toString();
}
 
Example 20
Project: ipst   File: CommentScanner.java   Source Code and License 6 votes vote down vote up
int skipQuoted(String line, Matcher quote, MatchResult q) {
    // First is a quote, skip until next (not escaped) quote is seen
    int p = q.end();
    int p1 = quoteRestart(q);
    MatchResult q1 = find(quote, p1);
    if (q1 == null) {
        // No more quotes in the line, we are inside a string not closed in this line
        eventHandler.onQuoted(line.substring(p), true, false);
        isInsideString = true;
        p = line.length();
    } else {
        // Emit this string and advance
        eventHandler.onQuoted(line.substring(p, quoteStart(q1)), true, true);
        p = q1.end();
    }
    return p;
}
 
Example 21
Project: ipst   File: CommentScanner.java   Source Code and License 6 votes vote down vote up
int skipBlockComment(String line, Matcher blockCommentEnd, MatchResult bcs) {
    // We go through a block comment start and look for a block comment end
    int p = bcs.end();
    MatchResult bce = find(blockCommentEnd, p);
    if (bce == null) {
        // No block comment end found in this line, start a multi-line comment
        eventHandler.onBlockComment(line.substring(p), true, false);
        isInsideBlockComment = true;
        p = line.length();
    } else {
        // Emit this block comment and advance
        eventHandler.onBlockComment(line.substring(p, bce.start()), true, true);
        p = bce.end();
    }
    return p;
}
 
Example 22
Project: PackageTemplates   File: RegexpHelperDialog.java   Source Code and License 6 votes vote down vote up
private void doMatch() {
    String pattern = tfPattern.getText();
    String text = tfText.getText();

    int matchCount = RegexHelper.matchCount(text, pattern);
    // Too much Matches
    if (matchCount > 1) {
        jlResult.setText(Localizer.get("error.MoreThenOneMatch"));
        jlResult.setIcon(AllIcons.RunConfigurations.TestFailed);
        return;
    }
    // No Matches
    if (matchCount <= 0) {
        jlResult.setText(Localizer.get("error.NoMatches"));
        jlResult.setIcon(AllIcons.RunConfigurations.TestFailed);
        return;
    }

    MatchResult matchResult = RegexHelper.match(text, pattern);

    jlResult.setText(String.format(Localizer.get("regexp.MatchSuccess"), matchResult.group()));
    jlResult.setIcon(AllIcons.RunConfigurations.TestPassed);
}
 
Example 23
Project: OBEP   File: PatternCollector.java   Source Code and License 6 votes vote down vote up
private TimePeriodExpression toTimeExpr() {
    Matcher matcher = p.matcher(within);
    if (matcher.find()) {
        MatchResult res = matcher.toMatchResult();
        if ("ms".equals(res.group(2))) {
            return Expressions.timePeriod(null, null, null, null, Integer.parseInt(res.group(1)));
        } else if ("s".equals(res.group(2))) {
            return Expressions.timePeriod(null, null, null, Integer.parseInt(res.group(1)), null);
        } else if ("m".equals(res.group(2))) {
            return Expressions.timePeriod(null, null, Integer.parseInt(res.group(1)), null, null);
        } else if ("h".equals(res.group(2))) {
            return Expressions.timePeriod(null, Integer.parseInt(res.group(1)), null, null, null);
        } else if ("d".equals(res.group(2))) {
            return Expressions.timePeriod(Integer.parseInt(res.group(1)), null, null, null, null);
        }
    }
    return null;
}
 
Example 24
Project: graylog-plugin-pipeline-processor   File: RegexMatch.java   Source Code and License 6 votes vote down vote up
public RegexMatchResult(boolean matches, MatchResult matchResult, List<String> groupNames) {
    this.matches = matches;
    ImmutableMap.Builder<String, String> builder = ImmutableMap.<String, String>builder();

    if (matches) {
        // arggggh! not 0 based.
        final int groupCount = matchResult.groupCount();
        for (int i = 1; i <= groupCount; i++) {
            final String groupValue = matchResult.group(i);

            if (groupValue == null) {
                // You cannot add null values to an ImmutableMap but optional matcher groups may be null.
                continue;
            }

            // try to get a group name, if that fails use a 0-based index as the name
            final String groupName = Iterables.get(groupNames, i - 1, null);
            builder.put(groupName != null ? groupName : String.valueOf(i - 1), groupValue);
        }
    }
    groups = builder.build();
}
 
Example 25
Project: java-restify   File: EndpointPathParameterResolver.java   Source Code and License 6 votes vote down vote up
private String path(Object[] args) {
	StringBuffer builder = new StringBuffer();

	Matcher matcher = DynamicParameterMatcher.matches(path);

	while (matcher.find()) {
		MatchResult match = matcher.toMatchResult();

		String name = match.group(1);

		parameters.find(name)
			.filter(p -> p.path())
				.ifPresent(p -> matcher.appendReplacement(builder,
						Optional.ofNullable(args[p.position()]).map(a -> p.resolve(a))
							.orElseThrow(() -> new IllegalArgumentException("Your path argument [" + name + "] cannot be null."))));
	}

	matcher.appendTail(builder);

	return builder.toString();
}
 
Example 26
Project: newsleak-frontend   File: HeidelTimeOpenNLP.java   Source Code and License 6 votes vote down vote up
/**
 * Check whether the part of speech constraint defined in a rule is satisfied.
 * @param s
 * @param posConstraint
 * @param m
 * @param jcas
 * @return
 */
public boolean checkPosConstraint(Sentence s, String posConstraint, MatchResult m, JCas jcas) {
	Pattern paConstraint = Pattern.compile("group\\(([0-9]+)\\):(.*?):");
	for (MatchResult mr : Toolbox.findMatches(paConstraint,posConstraint)) {
		int groupNumber = Integer.parseInt(mr.group(1));
		int tokenBegin = s.getBegin() + m.start(groupNumber);
		int tokenEnd   = s.getBegin() + m.end(groupNumber);
		String pos = mr.group(2);
		String pos_as_is = getPosFromMatchResult(tokenBegin, tokenEnd ,s, jcas);
		if (pos_as_is.matches(pos)) {
			Logger.printDetail("POS CONSTRAINT IS VALID: pos should be "+pos+" and is "+pos_as_is);
		} else {
			return false;
		}
	}
	return true;
}
 
Example 27
Project: jdk8u_jdk   File: TzdbZoneRulesCompiler.java   Source Code and License 6 votes vote down vote up
private int parseYear(Scanner s, int defaultYear) {
    if (s.hasNext(YEAR)) {
        s.next(YEAR);
        MatchResult mr = s.match();
        if (mr.group(1) != null) {
            return 1900;  // systemv has min
        } else if (mr.group(2) != null) {
            return YEAR_MAX_VALUE;
        } else if (mr.group(3) != null) {
            return defaultYear;
        }
        return Integer.parseInt(mr.group(4));
        /*
        if (mr.group("min") != null) {
            //return YEAR_MIN_VALUE;
            return 1900;  // systemv has min
        } else if (mr.group("max") != null) {
            return YEAR_MAX_VALUE;
        } else if (mr.group("only") != null) {
            return defaultYear;
        }
        return Integer.parseInt(mr.group("year"));
        */
    }
    throw new IllegalArgumentException("Unknown year: " + s.next());
}
 
Example 28
Project: lookaside_java-1.8.0-openjdk   File: TzdbZoneRulesCompiler.java   Source Code and License 6 votes vote down vote up
private int parseYear(Scanner s, int defaultYear) {
    if (s.hasNext(YEAR)) {
        s.next(YEAR);
        MatchResult mr = s.match();
        if (mr.group(1) != null) {
            return 1900;  // systemv has min
        } else if (mr.group(2) != null) {
            return YEAR_MAX_VALUE;
        } else if (mr.group(3) != null) {
            return defaultYear;
        }
        return Integer.parseInt(mr.group(4));
        /*
        if (mr.group("min") != null) {
            //return YEAR_MIN_VALUE;
            return 1900;  // systemv has min
        } else if (mr.group("max") != null) {
            return YEAR_MAX_VALUE;
        } else if (mr.group("only") != null) {
            return defaultYear;
        }
        return Integer.parseInt(mr.group("year"));
        */
    }
    throw new IllegalArgumentException("Unknown year: " + s.next());
}
 
Example 29
Project: EDDI   File: CallbackMatcher.java   Source Code and License 6 votes vote down vote up
public String replaceMatches(CharSequence charSequence, Callback callback) throws CallbackMatcherException {
    StringBuilder result = new StringBuilder(charSequence);
    final Matcher matcher = this.pattern.matcher(charSequence);
    int offset = 0;

    while (matcher.find()) {
        final MatchResult matchResult = matcher.toMatchResult();
        final String replacement = callback.foundMatch(matchResult);
        if (replacement == null) {
            continue;
        }

        int matchStart = offset + matchResult.start();
        int matchEnd = offset + matchResult.end();

        result.replace(matchStart, matchEnd, replacement);

        int matchLength = matchResult.end() - matchResult.start();
        int lengthChange = replacement.length() - matchLength;

        offset += lengthChange;
    }

    return result.toString();
}
 
Example 30
Project: communote-server   File: ValidationHelper.java   Source Code and License 6 votes vote down vote up
/**
 * Validates a string by regex expression
 *
 * @param input
 *            the input of a form field.
 * @param regex
 *            a regular expression for the given string, can be {@code null}
 * @param fieldName
 *            Name of the field the check is against.
 * @param errors
 *            The errors to put the error into.
 * @return The message key for the error.
 */
private static String doValidationAgainstRegex(String input, String regex, String fieldName,
        Errors errors) {
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(input == null ? "" : input);
    if (!matcher.matches()) {
        errors.rejectValue(fieldName, getRegexErrorMessageKey(regex),
                new Object[] { getRegexForDisplay(regex) }, "");
        return getRegexErrorMessageKey(regex);
    }
    MatchResult res = matcher.toMatchResult();
    if (res.start() != 0 || res.end() != input.length()) {
        errors.rejectValue(fieldName, getRegexErrorMessageKey(regex),
                new Object[] { getRegexForDisplay(regex) }, "");
        return getRegexErrorMessageKey(regex);
    }
    return null;
}
 
Example 31
Project: intellij-ce-playground   File: AbstractEditorTest.java   Source Code and License 6 votes vote down vote up
/**
 * Setups document of the {@link #getEditor() current editor} according to the given text that is expected to contain
 * information about document lines obtained from the {@link DocumentImpl#dumpState()}. 
 * 
 * @param data  string representation of the target document's lines
 */
@SuppressWarnings("UnusedDeclaration")
protected static void setupDocument(@NotNull String data) {
  Scanner scanner = new Scanner(data);
  Pattern pattern = Pattern.compile("(\\d+)\\s*:\\s*(\\d+)\\s*-\\s*(\\d+)");
  StringBuilder buffer = new StringBuilder();
  while (scanner.findInLine(pattern) != null) {
    final MatchResult match = scanner.match();
    int startOffset = Integer.parseInt(match.group(2));
    int endOffset = Integer.parseInt(match.group(3));
    buffer.append(StringUtil.repeatSymbol('a', endOffset - startOffset)).append('\n');
  }
  if (buffer.length() > 0) {
    buffer.setLength(buffer.length() - 1);
  }
  myEditor.getDocument().setText(buffer.toString());
}
 
Example 32
Project: openddr-java   File: WinCEMozillaSubBuilder.java   Source Code and License 6 votes vote down vote up
private void setWinCeVersion(OperatingSystem model) {
    //TODO: to be refined
    String osV = model.getVersion();
    if (osV == null) {
        return;

    } else if (!model.getMajorRevision().equals("1")) {
        return;
    }

    if (osV.matches(".*(\\d+).(\\d+).(\\d+).(\\d+).*")) {
        Scanner s = new Scanner(osV);
        s.findInLine(".*(\\d+).(\\d+).(\\d+).(\\d+).*");
        MatchResult result = s.match();
        if (result.group(1).equals("4")) {
            model.setMajorRevision("5");

        } else if (result.group(1).equals("6")) {
            model.setMajorRevision("6");

            if (result.group(3).equals("7")) {
                model.setMinorRevision("1");
            }
        }
    }
}
 
Example 33
Project: MyVidCoRe   File: MatcherStream.java   Source Code and License 6 votes vote down vote up
/**
 * Find with {@ink Pattern} within input and return as {@ink MatchResult} stream.
 *
 * @param pattern the pattern
 * @param input the input
 * @return the stream
 */
public static Stream<MatchResult> findMatches(Pattern pattern, CharSequence input) {
    Matcher matcher = pattern.matcher(input);

    Spliterator<MatchResult> spliterator = new Spliterators.AbstractSpliterator<MatchResult>(
        Long.MAX_VALUE, Spliterator.ORDERED | Spliterator.NONNULL) {
        @Override
        public boolean tryAdvance(Consumer<? super MatchResult> action) {
            if (!matcher.find())
                return false;
            action.accept(matcher.toMatchResult());
            return true;
        }
    };

    return StreamSupport.stream(spliterator, false);
}
 
Example 34
Project: EvenWurse   File: JGoogleAnalyticsTracker.java   Source Code and License 6 votes vote down vote up
/**
 * Define the proxy to use for all GA tracking requests.
 * <p>
 * Call this static method early (before creating any tracking requests).
 *
 * @param proxyAddr
 *            "addr:port" of the proxy to use; may also be given as URL
 *            ("http://addr:port/").
 */
public static void setProxy(String proxyAddr) {
    if (proxyAddr != null) {

        String oldProxyAddr = proxyAddr;
        // Split into "proxyAddr:proxyPort".
        proxyAddr = null;
        int proxyPort = 8080;
        try (Scanner s = new Scanner(oldProxyAddr)) {
            s.findInLine("(http://|)([^:/]+)(:|)([0-9]*)(/|)");
            MatchResult m = s.match();

            if (m.groupCount() >= 2) proxyAddr = m.group(2);

            if (m.groupCount() >= 4 && !(m.group(4).length() == 0)) proxyPort = Integer.parseInt(m.group(4));
        }

        if (proxyAddr != null) {
            SocketAddress sa = new InetSocketAddress(proxyAddr, proxyPort);
            setProxy(new Proxy(Type.HTTP, sa));
        }
    }
}
 
Example 35
Project: streamflyer   File: EmbeddedFlagUtilTest.java   Source Code and License 6 votes vote down vote up
private MatchResult match(String input, String regex, int flags, boolean matchExpected) {
    // match with flags
    Matcher matcher = Pattern.compile(regex, flags).matcher(input);
    assertEquals(matchExpected, matcher.find());
    MatchResult result = matcher;

    // match with inline flags
    Matcher matcherInline = Pattern.compile(util.embedFlags(regex, flags)).matcher(input);
    assertEquals(matchExpected, matcherInline.find());
    MatchResult resultInline = matcherInline;

    if (matchExpected) {
        assertEqualMatchResult(result, resultInline);
    }
    return result;
}
 
Example 36
Project: nexus-public   File: RegexMatcher.java   Source Code and License 6 votes vote down vote up
@Override
public boolean matches(final Context context) {
  checkNotNull(context);

  String path = context.getRequest().getPath();
  log.debug("Matching: {}~={}", path, pattern);
  final java.util.regex.Matcher m = pattern.matcher(path);

  if (m.matches()) {
    // expose match result in context
    context.getAttributes().set(State.class, new State()
    {
      @Override
      public MatchResult getMatchResult() {
        return m;
      }
    });
    return true;
  }

  // no match
  return false;
}
 
Example 37
Project: jfiveparse   File: TokenizerTest.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void test() {

    // unescape
    if (desc.doubleEscaped != null && desc.doubleEscaped) {

        Replacer doubleEscapedUnicode = new Replacer() {
            @Override
            public String apply(MatchResult result) {
                int val = Integer.parseInt(result.group(1), 16);
                return new String(new char[] { ((char) val) });
            }
        };
        String newInput = replaceAll(desc.input, "\\\\u([\\d\\w]{4})", doubleEscapedUnicode);
        desc.input = newInput;
        for (Object o : desc.output) {
            if (isCharacterToken(o) || isCommentToken(o)) {
                List<String> token = (List<String>) o;
                token.set(1, replaceAll(token.get(1), "\\\\u([\\d\\w]{4})", doubleEscapedUnicode));
            }
        }
    }

    checkSingleTest(desc, state);
}
 
Example 38
Project: streamflyer   File: StateMachine.java   Source Code and License 6 votes vote down vote up
@Override
public MatchProcessorResult process(StringBuilder characterBuffer, int firstModifiableCharacterInBuffer,
        MatchResult matchResult) {

    // modify stream
    MatchProcessorResult result = transitions.process(characterBuffer, firstModifiableCharacterInBuffer,
            matchResult);

    // change state if needed
    State newState = transitions.pollNewState();
    if (newState != currentState) {
        changeStateTo(newState);
    }

    return result;
}
 
Example 39
Project: inbot-utils   File: MiscUtils.java   Source Code and License 6 votes vote down vote up
public static Stream<MatchResult> streamMatches(Matcher matcher) {
    // thank you SO: https://stackoverflow.com/questions/28148483/how-do-i-create-a-stream-of-regex-matches

    Spliterator<MatchResult> spliterator = new Spliterators.AbstractSpliterator<MatchResult>(Long.MAX_VALUE, Spliterator.ORDERED|Spliterator.NONNULL) {

        @Override
        public boolean tryAdvance(Consumer<? super MatchResult> action) {
            if(!matcher.find()) {
                return false;
            } else {
                action.accept(matcher.toMatchResult());
                return true;
            }
        }};

    return StreamSupport.stream(spliterator, false);
}
 
Example 40
Project: streamflyer   File: NoMatchAwareMatchProcessor.java   Source Code and License 6 votes vote down vote up
@Override
public MatchProcessorResult process(StringBuilder characterBuffer, int firstModifiableCharacterInBuffer,
        MatchResult matchResult) {

    // are there characters that belong to a noMatch?
    if (processNoMatch && noMatch.getStartPosition() < matchResult.start()) {
        // -> process the noMatch
        matchResult = noMatch.processNoMatch(characterBuffer, firstModifiableCharacterInBuffer, matchResult);
    }

    MatchProcessorResult result = delegate.process(characterBuffer, firstModifiableCharacterInBuffer, matchResult);

    // set the start position of the next noMatch
    noMatch.setStartPosition(result.getFirstModifiableCharacterInBuffer());

    return result;
}
 
Example 41
Project: FreeBuilder   File: TypeMirrors.java   Source Code and License 6 votes vote down vote up
/**
 * Evaluate generics and arrays depth-first, and substitute %d strings in their place.
 *   e.g.  %1<%2,%3<%4>>  -->  %1<%2,%5>  -->  %6
 */
private static void substituteGenericsAndArrays(
    Types typeUtils,
    MutableString snippet,
    Substitutions substitutions) {
  for (MatchResult m : snippet.instancesOf(GENERIC_OR_ARRAY_PATTERN)) {
    // Group 1 is the type on the left, e.g. '%1' in '%1<%2,%5>'
    // Group 2 contains the array brackets if this is an array, e.g. '[]' in '%1[]'
    // Group 3 contains the type list if this is a generic type, e.g. '%2,%5' in '%1<%2,%5>'
    TypeMirror type = substitutions.get(m.group(1));
    if (Strings.isNullOrEmpty(m.group(2))) {
      List<TypeMirror> argTypes = Lists.transform(
          Splitter.on(",").trimResults().splitToList(m.group(3)),
          substitutions.asFunction());
      snippet.replace(m, substitutions.put(parameterisedType(typeUtils, type, argTypes)));
    } else {
      snippet.replace(m, substitutions.put(typeUtils.getArrayType(type)));
    }
  }
}
 
Example 42
Project: greenpepper   File: Expression.java   Source Code and License 6 votes vote down vote up
/**
    * <p>parseVariableName.</p>
    *
    * @return a {@link java.lang.String} object.
    */
   public String parseVariableName() {
   	if(asString == null)
   		return null;
   	
   	String var = asString.trim();
   	if(!var.startsWith("$"))
   		throw new IllegalStateException("This expression is not a variable reference");
   	
   	Scanner scanner = new Scanner(var.substring(1));
   	scanner.findInLine("\\{\\s*(\\w+)\\s*\\}");
   	MatchResult matchResults = scanner.match();
   	if(matchResults.groupCount() != 1)
   		throw new IllegalStateException("Malformed variable name expression.");
   		
	return matchResults.group(1);
}
 
Example 43
Project: streamflyer   File: TokenProcessor.java   Source Code and License 6 votes vote down vote up
@Override
public MatchProcessorResult process(StringBuilder characterBuffer, int firstModifiableCharacterInBuffer,
        MatchResult matchResult) {

    // find out which token is matched
    int groupOffset = 1;
    for (Token token : tokens) {
        int groupsInToken = token.getCapturingGroupCount();

        String matchedGroup = matchResult.group(groupOffset);
        if (matchedGroup != null) {
            // this token is matched! -> process this token + return the result
            return processToken(token, characterBuffer, firstModifiableCharacterInBuffer,
                    new MatchResultWithOffset(matchResult, groupOffset));
        }

        groupOffset += groupsInToken + 1;
    }

    throw new RuntimeException("never to happen if used with " + TokensMatcher.class);
}
 
Example 44
Project: AndroidCourses   File: SystemUtils.java   Source Code and License 6 votes vote down vote up
private static MatchResult matchSystemFile(final String pSystemFile, final String pPattern, final int pHorizon) throws SystemUtilsException {
	InputStream in = null;
	try {
		final Process process = new ProcessBuilder(new String[] {"/system/bin/cat", pSystemFile}).start();

		in = process.getInputStream();
		final Scanner scanner = new Scanner(in);

		final boolean matchFound = scanner.findWithinHorizon(pPattern, pHorizon) != null;
		if (matchFound) {
			return scanner.match();
		} else {
			throw new SystemUtilsException();
		}
	} catch (final IOException e) {
		throw new SystemUtilsException(e);
	} finally {
		StreamUtils.close(in);
	}
}
 
Example 45
Project: openchemlib   File: StringFunctions.java   Source Code and License 6 votes vote down vote up
/**
 * 
 * @param str
 * @param regex
 * @return null if substring not found.
 */
public static String getStringFromRegEx(String str, String regex) {

	Pattern pa = Pattern.compile(regex);
   	
   	Matcher ma = pa.matcher(str);
   	
	int start = -1;
	int end = -1;
	
   	if(ma.find()){
   		MatchResult mr = ma.toMatchResult();
   		start = mr.start();
   		end = mr.end();
   	} else {
   		return null;
   	}

	return str.substring(start,end);
}
 
Example 46
Project: janala2-gradle   File: Scanner.java   Source Code and License 6 votes vote down vote up
/**
 * Returns true if there is another line in the input of this scanner.
 * This method may block while waiting for input. The scanner does not
 * advance past any input.
 *
 * @return true if and only if this scanner has another line of input
 * @throws IllegalStateException if this scanner is closed
 */
public boolean hasNextLine() {
    saveState();

    String result = findWithinHorizon(linePattern(), 0);
    if (result != null) {
        MatchResult mr = this.match();
        String lineSep = mr.group(1);
        if (lineSep != null) {
            result = result.substring(0, result.length() -
                                      lineSep.length());
            cacheResult(result);

        } else {
            cacheResult();
        }
    }
    revertState();
    return (result != null);
}
 
Example 47
Project: testclient   File: ScopedGeneratorCache.java   Source Code and License 6 votes vote down vote up
private void parse(String generatorSpec) {
    Matcher m = scopeAndSpec.matcher(generatorSpec);
    if (!m.matches()) {
        throw new RuntimeException("Unable to match generator spec with pattern: " + scopeAndSpec.pattern() + ", generator spec: " + generatorSpec);
    }
    MatchResult matchResult = m.toMatchResult();

    String genscope = matchResult.group(2);
    String genspec = matchResult.group(3);
    logger.trace("genscope:" + genscope + ", genspec" + genspec);

    if (matchResult.group(2) == null) {
        this.runtimeScope = defaultScope;
    } else {
        this.runtimeScope = RuntimeScope.valueOf(genscope);
    }

    this.generatorSpec = genspec;

}
 
Example 48
Project: APICloud-Studio   File: FormatterPreviewUtils.java   Source Code and License 6 votes vote down vote up
/**
 * Do a content substitution by looking at the array size and looking for {0}...{n} strings and replace them with
 * the array's content.<br>
 * (Note - we use this method and not the NLS.bind() because it does not handle well code blocks existence)
 * 
 * @param content
 * @param substitutions
 * @return A string, substituted with the array's content.
 */
private static String substitute(String content, String[] substitutions)
{
	StringBuilder buffer = new StringBuilder(content);
	Matcher matcher = SUBSTITUTION_PATTERN.matcher(content);
	int offset = 0;
	while (matcher.find())
	{
		MatchResult matchResult = matcher.toMatchResult();
		int beginIndex = matchResult.start();
		int endIndex = matchResult.end();
		int index = Integer.parseInt(content.substring(beginIndex + 1, endIndex - 1));
		if (index >= 0 && index < substitutions.length)
		{
			String replacement = substitutions[index];
			int matchLength = endIndex - beginIndex;
			buffer.replace(offset + beginIndex, offset + endIndex, replacement);
			offset += (replacement.length() - matchLength);
		}
	}
	return buffer.toString();
}
 
Example 49
Project: mr4c   File: CustomFormat.java   Source Code and License 6 votes vote down vote up
public Map<String,String> parse(String str) {
	if ( !matches(str) ) {
		throw new IllegalArgumentException(String.format("[%s] doesn't match pattern [%s]", str, m_pattern));
	}
	Scanner scanner = new Scanner(str);
	scanner.findWithinHorizon(m_regex, 0);
	MatchResult result = scanner.match();
	Map<String,String> vals = new HashMap<String,String>();
	if ( result.groupCount()!=m_nameList.size() ) {
		// this shouldn't be able to happen
		throw new IllegalStateException(String.format("[%s] doesn't match pattern [%s]; found %d matches, expected %d", str, m_pattern, result.groupCount(), m_nameList.size()));
	}
	for (int i=1; i<=result.groupCount(); i++) {
		String name = m_nameList.get(i-1);
		String val = result.group(i);
		if ( vals.containsKey(name) ) {
			if ( !vals.get(name).equals(val) ) {
				throw new IllegalArgumentException(String.format("[%s]doesnt match pattern [%s]; variable [%s] has values [%s] and [%s]", str, m_pattern, name, val, vals.get(name)));
			}
		}
		vals.put(name,result.group(i));
	}
	return vals;
}
 
Example 50
Project: jdk8u-dev-jdk   File: TzdbZoneRulesCompiler.java   Source Code and License 6 votes vote down vote up
private int parseYear(Scanner s, int defaultYear) {
    if (s.hasNext(YEAR)) {
        s.next(YEAR);
        MatchResult mr = s.match();
        if (mr.group(1) != null) {
            return 1900;  // systemv has min
        } else if (mr.group(2) != null) {
            return YEAR_MAX_VALUE;
        } else if (mr.group(3) != null) {
            return defaultYear;
        }
        return Integer.parseInt(mr.group(4));
        /*
        if (mr.group("min") != null) {
            //return YEAR_MIN_VALUE;
            return 1900;  // systemv has min
        } else if (mr.group("max") != null) {
            return YEAR_MAX_VALUE;
        } else if (mr.group("only") != null) {
            return defaultYear;
        }
        return Integer.parseInt(mr.group("year"));
        */
    }
    throw new IllegalArgumentException("Unknown year: " + s.next());
}
 
Example 51
Project: craftf   File: MarkupParser.java   Source Code and License 6 votes vote down vote up
public void parse(Element parent, String input) {

		//Scanner src = new Scanner(input);
		AtomicInteger pointer = new AtomicInteger(0);

		loop: while(pointer.get() < input.length()) {
			String src = null;
			for(ParserExtension ext: extensions) {

				MatchResult match = nextMatch(src = input.substring(pointer.get()), ext.getRegex());

				//System.out.println("\"" + escaped + "\": attempting " + ext.getClass().getSimpleName());
				if(match == null) continue;
				//System.out.println("\"" + escaped + "\": matched \"" + CraftF.escapeText(match.group()) + "\" @ " + pointer);
				ext.parse(this, parent, match);
				pointer.addAndGet(match.end());
				continue loop;
			}
			System.out.println("\"" + CraftF.escapeText(src) + "\": no parsers were found @ " + pointer);
			break;
		}
		//src.close();
	}
 
Example 52
Project: streamflyer   File: AbstractMatchProcessor.java   Source Code and License 6 votes vote down vote up
/**
 * @param matchResult
 *            the {@link MatchResult} given to the {@link MatchProcessor}.
 * @param newMatchEnd
 *            the position of the end of the matched string after the character buffer is modified.
 * @param continueMatching
 *            See {@link MatchProcessorResult#isContinueMatching()}
 * @return Returns a {@link MatchProcessorResult} that cannot cause an endless loop.
 */
protected MatchProcessorResult createResult(MatchResult matchResult, int newMatchEnd, boolean continueMatching) {

    int matchStart = matchResult.start();
    int matchEnd = matchResult.end();

    // if the empty string is matched, then we increase the position
    // to avoid endless loops
    // (compare to Matcher.find() where we see the following code:
    // int i = last; if(i == first) i++;
    // in words: set the *from* for the next match at the
    // end of the last match. if this is equal to the start
    // of the last match (a match on the empty string(, then
    // increase the *from* to avoid endless loops)
    int offset = matchStart == matchEnd ? 1 : 0;

    return new MatchProcessorResult(newMatchEnd + offset, continueMatching);
}
 
Example 53
Project: opendocs   File: AttributeInfo.java   Source Code and License 6 votes vote down vote up
private Location[] getAttributStartEnd(String attributRegion, Location locStart, Node attr) {
		Location[] startEnd = new Location[2];
		Matcher matcher = attrPattern.matcher(attributRegion);
//		debug-error! can not be debugged...
		while (matcher.find()) {
			String name = matcher.group(1);
			if (name.equals(attr.getNodeName())) {

				MatchResult mresult = matcher.toMatchResult();
				int startPos = mresult.start();
				int endPos = mresult.end();
				startEnd[0] = NodeInfo.newLocation(locStart, startPos);
				startEnd[1] = NodeInfo.newLocation(locStart, endPos);
				break;
			}
		}
		return startEnd;
	}
 
Example 54
Project: OQLMapper   File: StringUtils.java   Source Code and License 6 votes vote down vote up
public static String regexReplaceAll(String source, String regexString, Function<MatchResult, String> replaceFunction)  {
	if (source == null || source.trim().isEmpty()) // avoid NPE's, save CPU
		return "";

	StringBuffer resultString = new StringBuffer();
	Pattern regex = Pattern.compile(regexString);
	Matcher regexMatcher = regex.matcher(source);
	
	while (regexMatcher.find()) {
		MatchResult match = regexMatcher.toMatchResult();
		String value = replaceFunction.apply(match); 
		regexMatcher.appendReplacement(resultString, Matcher.quoteReplacement(value));
	}
	regexMatcher.appendTail(resultString);

	return resultString.toString();
}
 
Example 55
Project: wildfly-swarm-fraction-plugin   File: ModuleFiller.java   Source Code and License 6 votes vote down vote up
private Map<String, Artifact> processFeaturePackXml(InputStream in) throws IOException {
    final Map<String, Artifact> artifacts = new HashMap<>();
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(in))) {
        String line = null;

        while ((line = reader.readLine()) != null) {
            line = line.trim();

            Matcher matcher = ARTIFACT_PATTERN.matcher(line);
            if (matcher.matches()) {
                MatchResult result = matcher.toMatchResult();

                String groupId = result.group(1);
                String artifactId = result.group(2);
                String version = result.group(3);
                String classifier = result.group(5);

                String expr = groupId + ":" + artifactId + (classifier == null ? "" : "::" + classifier);

                artifacts.put(expr, new DefaultArtifact(groupId, artifactId, classifier, "jar", version));
            }
        }
    }
    return artifacts;
}
 
Example 56
Project: streamflyer   File: RangeFilterState.java   Source Code and License 6 votes vote down vote up
/**
 * @see com.github.rwitzel.streamflyer.experimental.stateful.util.RegexTransitionState#modifyBuffer(java.lang.StringBuilder,
 *      int, java.util.regex.MatchResult)
 */
@Override
protected int modifyBuffer(StringBuilder characterBuffer, int firstModifiableCharacterInBuffer,
        MatchResult matchResult) {

    int shiftMatchResult = 0;

    // delete characters before token
    if (deleteCharactersBeforeToken) {
        characterBuffer.delete(firstModifiableCharacterInBuffer, matchResult.start());
        shiftMatchResult += matchResult.start() - firstModifiableCharacterInBuffer;
    }

    // delete token
    if (deleteToken) {
        characterBuffer.delete(matchResult.start() - shiftMatchResult, matchResult.end() - shiftMatchResult);
        shiftMatchResult += matchResult.end() - matchResult.start();
    }

    return matchResult.end() - shiftMatchResult;
}
 
Example 57
Project: ClassicF1   File: SystemUtils.java   Source Code and License 6 votes vote down vote up
private static MatchResult matchSystemFile(final String pSystemFile, final String pPattern, final int pHorizon) throws SystemUtilsException {
	InputStream in = null;
	try {
		final Process process = new ProcessBuilder(new String[] { "/system/bin/cat", pSystemFile }).start();

		in = process.getInputStream();
		final Scanner scanner = new Scanner(in);

		final boolean matchFound = scanner.findWithinHorizon(pPattern, pHorizon) != null;
		if(matchFound) {
			return scanner.match();
		} else {
			throw new SystemUtilsException();
		}
	} catch (final IOException e) {
		throw new SystemUtilsException(e);
	} finally {
		StreamUtils.close(in);
	}
}
 
Example 58
Project: eHMP   File: VistaStringUtils.java   Source Code and License 6 votes vote down vote up
private static String replaceAll(Pattern pattern, CharSequence charSequence, Callback callback) {
    Matcher matcher = pattern.matcher(charSequence);
    StringBuilder sb = new StringBuilder(charSequence);
    int offset = 0;
    while (matcher.find()) {
        MatchResult matchResult = matcher.toMatchResult();

        String replacement = callback.foundMatch(matchResult);

        int matchStart = offset + matchResult.start();
        int matchEnd = offset + matchResult.end();

        sb.replace(matchStart, matchEnd, replacement);

        int matchLength = matchResult.end() - matchResult.start();
        int lengthChange = replacement.length() - matchLength;

        offset += lengthChange;
    }
    return sb.toString();
}
 
Example 59
Project: streamflyer   File: LineColumnOnRegexMatchTest.java   Source Code and License 6 votes vote down vote up
@Override
public MatchProcessorResult process(StringBuilder characterBuffer, int firstModifiableCharacterInBuffer,
        MatchResult matchResult) {

    long unmatchedStartLine = fac.getCurrentLine();
    long unmatchedStartColumn = fac.getCurrentColumn();
    int unmatchedStart = firstCharIndex;
    int unmatchedEnd = matchResult.start();
    String unmatched = characterBuffer.substring(unmatchedStart, unmatchedEnd);

    String matchPosition = matchPosition(unmatchedStartLine, unmatchedStartColumn, unmatched);

    matchPositions.add(matchPosition);

    return super.process(characterBuffer, firstModifiableCharacterInBuffer, matchResult);
}
 
Example 60
Project: demyo   File: RteTool.java   Source Code and License 6 votes vote down vote up
/**
 * Replaces models links like "Author:2" to actual controller references.
 * 
 * @param text The text to parse.
 * @param contextRoot The context root, used to resolve links.
 * @return The filtered text.
 */
private CharSequence replaceModelLinks(CharSequence text, String contextRoot) {
	StringBuffer resultString = new StringBuffer();
	Pattern regex = Pattern.compile(PATTERN_MODEL_LINKS);
	Matcher regexMatcher = regex.matcher(text);
	while (regexMatcher.find()) {
		MatchResult result = regexMatcher.toMatchResult();
		String model = result.group(GROUP_MODEL_LINKS_MODEL);
		String controller = MODEL_TO_CONTROLLER.get(model);
		if (controller == null) {
			controller = model; // fallback
		}
		String id = result.group(GROUP_MODEL_LINKS_ID);
		regexMatcher.appendReplacement(resultString, "href=\"" + contextRoot + "/" + controller + "/view/"
				+ id + "\"");
	}
	regexMatcher.appendTail(resultString);
	return resultString;
}