java.util.regex.MatchResult Java Examples

The following examples show how to use java.util.regex.MatchResult. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DefaultFormat.java    From openjdk-jdk9 with GNU General Public License v2.0 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 #2
Source File: BatchResponseParser.java    From cloud-odata-java with Apache License 2.0 6 votes vote down vote up
private Map<String, String> parseResponseHeaders(final Scanner scanner) throws BatchException {
  Map<String, String> headers = new HashMap<String, String>();
  while (scanner.hasNext() && !scanner.hasNext(REG_EX_BLANK_LINE)) {
    if (scanner.hasNext(REG_EX_HEADER)) {
      scanner.next(REG_EX_HEADER);
      currentLineNumber++;
      MatchResult result = scanner.match();
      if (result.groupCount() == 2) {
        String headerName = result.group(1).trim();
        String headerValue = result.group(2).trim();
        if (BatchHelper.HTTP_CONTENT_ID.equalsIgnoreCase(headerName)) {
          if (currentContentId == null) {
            currentContentId = headerValue;
          }
        } else {
          headers.put(headerName, headerValue);
        }
      }
    } else {
      currentLineNumber++;
      throw new BatchException(BatchException.INVALID_HEADER.addContent(scanner.next()).addContent(currentLineNumber));
    }
  }
  return headers;
}
 
Example #3
Source File: StringUtils.java    From RestServices with Apache License 2.0 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./]+)\\}", (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 #4
Source File: TzdbZoneRulesCompiler.java    From dragonwell8_jdk with GNU General Public License v2.0 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 #5
Source File: CustomFormat.java    From mr4c with Apache License 2.0 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 #6
Source File: TzdbZoneRulesCompiler.java    From jdk8u60 with GNU General Public License v2.0 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 #7
Source File: TzdbZoneRulesCompiler.java    From jdk8u_jdk with GNU General Public License v2.0 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 #8
Source File: FindReplaceDialog.java    From nextreports-designer with Apache License 2.0 6 votes vote down vote up
/**
 * Search from same startIndex as the previous search. 
 * Checks if the match is different from the last (either 
 * extended/reduced) at the same position. Returns true
 * if the current match result represents a different match 
 * than the last, false if no match or the same.
 */
private boolean foundExtendedMatch(Pattern pattern, int start) {
    if (pattern.pattern().equals(lastRegex)) {
        return false;
    }
    
    int length = target.getDocument().getLength() - start;
    try {
        target.getDocument().getText(start, length, segment);
    } catch (BadLocationException e) {
    	e.printStackTrace();
    }
    
    Matcher matcher = pattern.matcher(segment.toString());
    MatchResult matchResult = getMatchResult(matcher, true);
    if (matchResult != null) {
        if ((matchResult.start() == 0) &&  (!lastMatchResult.group().equals(matchResult.group()))) {
            updateStateAfterFound(matchResult, start);
            return true;
        } 
    }
    
    return false;
}
 
Example #9
Source File: ElasticGazetteerAcceptanceTest.java    From CogStack-Pipeline with Apache License 2.0 6 votes vote down vote up
private int getTruePositiveTokenCount( Mutant mutant){
    int count = 0;
    Pattern mask = Pattern.compile("X+");
    List<MatchResult> results = new ArrayList<>();
    Matcher matcher = mask.matcher(mutant.getDeidentifiedString());
    while (matcher.find()){
        results.add(matcher.toMatchResult());
    }
    for(MatchResult result: results) {
        StringTokenizer tokenizer = new StringTokenizer(mutant.getFinalText().substring(result.start(),result.end()));
        ArrayList<String> arHits = new ArrayList<>();
        while (tokenizer.hasMoreTokens()){
            arHits.add(tokenizer.nextToken());
        }
        count = getHitCount(mutant, count, arHits);
    }
    return count;
}
 
Example #10
Source File: SystemUtils.java    From tilt-game-android with MIT 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 #11
Source File: TzdbZoneRulesCompiler.java    From hottub with GNU General Public License v2.0 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 #12
Source File: UriTemplate.java    From RestServices with Apache License 2.0 6 votes vote down vote up
public String createURI(final Map<String, String> values) {
	Preconditions.checkNotNull(values);
	
	Preconditions.checkArgument(values.keySet().equals(new HashSet<String>(paramNames)), "Incomplete set of values for path " + pathString + ", expected the following keys: " + paramNames + ", found: " + values.keySet());
	
	return regexReplaceAll(pathString, PARAMNAME_REGEX,  new Function<MatchResult, String>() {

		@Override
		public String apply(MatchResult match) {
			String paramName = match.group(1);
			String value = values.get(paramName);
			if (value == null || value.isEmpty()) {
				throw new IllegalArgumentException("No value was defined for path element '{" + paramName + "}'. The value should be non-empty.");
			}
			return Utils.urlEncode(values.get(paramName));
		}
	});
}
 
Example #13
Source File: TzdbZoneRulesCompiler.java    From jdk8u-jdk with GNU General Public License v2.0 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 #14
Source File: QueryManager.java    From CostFed with GNU Affero General Public License v3.0 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
Source File: DefaultFormat.java    From openjdk-jdk9 with GNU General Public License v2.0 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
Source File: RewriteConfig.java    From styx with Apache License 2.0 6 votes vote down vote up
private String substitute(MatchResult matcher) {
    StringBuilder rewrittenUrl = new StringBuilder();

    // There may not be enough literals to fully interleave with placeholders.
    // This is just how String.split(REGEX) works.
    // Any remaining literals are assumed to be empty strings.
    for (int i = 0; i < placeholderNumbers.size(); i++) {
        if (literals.size() > i) {
            rewrittenUrl.append(literals.get(i));
        }
        rewrittenUrl.append(matcher.group(placeholderNumbers.get(i)));
    }

    if (literals.size() > placeholderNumbers.size()) {
        rewrittenUrl.append(literals.get(literals.size() - 1));
    }

    return rewrittenUrl.toString();
}
 
Example #17
Source File: PercentToBraceConverter.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Build a group dictionary from the matched groups. <br>
 * Guaranteed to contain 4 keys:<br>
 * <ol>
 *   <li><tt>FormatString</tt>: the complete format string part</li>
 *   <li><tt>StringCharacter</tt>: the literal delimiter used (e.g. <tt>",',''',"""</tt></li>
 *   <li><tt>InterpolantToken</tt>: the percent sign, used to signal string interpolation</li>
 *   <li><tt>InterpolationValues</tt>: the values for filling in the specifier tokens in the format string.</li>
 * </ol>
 * @param matchResult
 * @return the K, V mapped groups.
 * @see {@link #FMTSTR_PATTERN}
 */
private static Map<String, String> extractFormatStringGroups(final MatchResult matchResult) {

    // in a strict sense the assertion here is superfluous since the enclosing 
    // context in the caller already does a check if the group count is 4 and 
    // the execution branch in which this method is called will not be run if
    // it isn't 4.
    Assert.isLegal(4 == matchResult.groupCount(),
            "E: Match result from FMTSTR_PATTERN is malformed. Group count must be 4.");

    final Map<String, String> result = new HashMap<String, String>(4);

    final String fmtString = matchResult.group(1);
    final String strChar = matchResult.group(2);
    final String interpToken = matchResult.group(3);
    final String interpValues = matchResult.group(4);

    result.put("FormatString", fmtString);
    result.put("StringCharacter", strChar);
    result.put("InterpolantToken", interpToken);
    result.put("InterpolationValues", interpValues);

    return result;
}
 
Example #18
Source File: TzdbZoneRulesCompiler.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 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 #19
Source File: TzdbZoneRulesCompiler.java    From openjdk-jdk8u with GNU General Public License v2.0 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 #20
Source File: PluginMessagesCLIResult.java    From thym with Eclipse Public License 1.0 6 votes vote down vote up
private void parseMessage(){
	
	Scanner scanner = new Scanner(getMessage());
	
	while(scanner.hasNextLine()){
		//check of --variable APP_ID=value is needed
		if( scanner.findInLine("(?:\\s\\-\\-variable\\s(\\w*)=value)") != null ){
			MatchResult mr = scanner.match();
			StringBuilder missingVars = new StringBuilder();
			for(int i = 0; i<mr.groupCount();i++){
				if(i>0){
					missingVars.append(",");
				}
				missingVars.append(mr.group());
			}
			pluginStatus = new HybridMobileStatus(IStatus.ERROR, HybridCore.PLUGIN_ID, CordovaCLIErrors.ERROR_MISSING_PLUGIN_VARIABLE,
					NLS.bind("This plugin requires {0} to be defined",missingVars), null);
		
		}
		scanner.nextLine();
	}
	scanner.close();
	
}
 
Example #21
Source File: Strings.java    From sinavi-jfw with Apache License 2.0 6 votes vote down vote up
/**
 * 引数の文字列をラクダ記法(単語区切りが大文字)とみなして、
 * それを全て大文字のスネーク記法(単語区切りがアンダースコア)に変換します。
 * 例えば、ラクダ記法の<code>tigerSupportApi</code>は、
 * スネーク記法の<code>TIGER_SUPPORT_API</code>に変換されます。
 * @param camel ラクダ記法の文字列
 * @return スネーク記法(全て大文字)
 */
public static String toSnake(String camel) {
    if (Strings.isBlank(camel))
        return "";

    ArrayList<String> words = new ArrayList<String>();

    Matcher matcher = SNAKE_CASE_WORD.matcher(camel);
    while(matcher.find()) {
        MatchResult result = matcher.toMatchResult();
        String word = camel.substring(result.start(), result.end());

        words.add(word.toUpperCase());
    }
    return Strings.joinBy("_", words);
}
 
Example #22
Source File: RegexMatcher.java    From nexus-public with Eclipse Public License 1.0 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 #23
Source File: GroupId.java    From liiklus with MIT License 6 votes vote down vote up
public static GroupId ofString(String str) {
    Matcher matcher = VERSION_PATTERN.matcher(str);

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

        return GroupId.of(
                result.group(1),
                Optional.ofNullable(result.group(2)).map(Integer::parseInt)
        );
    } else {
        return GroupId.of(
                str,
                Optional.empty()
        );
    }
}
 
Example #24
Source File: RegExpPrototype.java    From es6draft with MIT License 6 votes vote down vote up
/**
 * 21.2.5.2.1 Runtime Semantics: RegExpExec ( R, S ) (1)
 * 
 * @param cx
 *            the execution context
 * @param r
 *            the regular expression object
 * @param s
 *            the string
 * @param storeResult
 *            {@code true} if the match result is stored
 * @return the match result object or null
 */
private static MatchResult matchResultOrNull(ExecutionContext cx, ScriptObject r, String s, boolean storeResult) {
    /* steps 1-2 (not applicable) */
    /* step 3 */
    Object exec = Get(cx, r, "exec");
    /* step 4 */
    // Don't take the slow path for built-in RegExp.prototype.exec
    if (IsCallable(exec) && !isBuiltinExec(cx.getRealm(), exec)) {
        ScriptObject o = RegExpUserExec(cx, (Callable) exec, r, s);
        return o != null ? new ScriptObjectMatchResult(cx, o) : null;
    }
    /* step 5 */
    RegExpObject rx = thisRegExpObject(cx, r, "RegExp.prototype.exec");
    /* step 6 */
    return matchResultOrNull(cx, rx, s, storeResult);
}
 
Example #25
Source File: ParserTest.java    From riposte with Apache License 2.0 5 votes vote down vote up
@Test
public void test_regex_parser_parse_works () throws ParserFailure {
    Parser<MatchResult> parser = regex("^.*(test).*$");
    MatchResult successResult = parser.parse("this test should work");
    assertThat(successResult.groupCount()).isEqualTo(1);
    assertThat(successResult.group(1)).isEqualTo("test");
}
 
Example #26
Source File: JsEmbeddingProvider.java    From netbeans with Apache License 2.0 5 votes vote down vote up
protected static List<EmbeddingPosition> extractJsEmbeddings(String text, int sourceStart) {
    List<EmbeddingPosition> embeddings = new LinkedList<EmbeddingPosition>();
    // beggining comment around the script
    int start = 0;
    for (; start < text.length(); start++) {
        char c = text.charAt(start);
        if (!Character.isWhitespace(c)) {
            break;
        }
    }
    if (start < text.length() && text.startsWith("<!--", start)) { //NOI18N
        int lineEnd = text.indexOf('\n', start); //NOI18N
        if (isHtmlCommentStartToSkip(text, start, lineEnd)) {
            if (start > 0) {
                embeddings.add(new EmbeddingPosition(sourceStart, start));
            }
            lineEnd++; //skip the \n
            sourceStart += lineEnd;
            text = text.substring(lineEnd);
        }
    }

    // inline comments inside script
    Scanner scanner = new Scanner(text).useDelimiter("(<!--).*(-->)"); //NOI18N
    while (scanner.hasNext()) {
        scanner.next();
        MatchResult match = scanner.match();
        embeddings.add(new EmbeddingPosition(sourceStart + match.start(), match.group().length()));
    }
    return embeddings;
}
 
Example #27
Source File: MoreAsserts.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Asserts that {@code expectedRegex} matches any substring of {@code actual}
 * and fails with {@code message} if it does not.  The Matcher is returned in
 * case the test needs access to any captured groups.  Note that you can also
 * use this for a literal string, by wrapping your expected string in
 * {@link Pattern#quote}.
 */
public static MatchResult assertContainsRegex(
        String message, String expectedRegex, String actual) {
    if (actual == null) {
        failNotContains(message, expectedRegex, actual);
    }
    Matcher matcher = getMatcher(expectedRegex, actual);
    if (!matcher.find()) {
        failNotContains(message, expectedRegex, actual);
    }
    return matcher;
}
 
Example #28
Source File: MatchResultSubstitution.java    From common-utils with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected String group(int index, int groupNumber) {
    MatchResult result = getMatch(index);

    if (0 <= groupNumber && groupNumber <= result.groupCount()) {
        return result.group(groupNumber);
    }

    return null;
}
 
Example #29
Source File: ParserTest.java    From riposte with Apache License 2.0 5 votes vote down vote up
@Test
public void test_regex_parser_try_parse_works () throws ParserFailure {
    Parser<MatchResult> parser = regex("^.*(test).*$");
    Optional<MatchResult> successResult = parser.tryParse("this test should work");
    assertThat(successResult.isPresent()).isTrue();
    assertThat(successResult.get()).isNotNull();
    assertThat(successResult.get().groupCount()).isEqualTo(1);
    assertThat(successResult.get().group(1)).isEqualTo("test");
}
 
Example #30
Source File: Evaluator.java    From java-repl with Apache License 2.0 5 votes vote down vote up
private Either<Throwable, Expression> createAssignmentWithType(String expression) {
    try {
        MatchResult match = Patterns.assignmentWithTypeNamePattern.match(expression);
        java.lang.reflect.Method declaredMethod = detectMethod(match.group(1) + " " + randomIdentifier("method") + "(){}");
        return right((Expression) new AssignmentWithType(expression, declaredMethod.getGenericReturnType(), match.group(2), match.group(3)));
    } catch (Exception e) {
        return left(Utils.unwrapException(e));
    }
}