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 Project: RestServices Author: mendix File: StringUtils.java License: Apache License 2.0 | 6 votes |
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 #2
Source Project: dragonwell8_jdk Author: alibaba File: TzdbZoneRulesCompiler.java License: GNU General Public License v2.0 | 6 votes |
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 #3
Source Project: jdk8u_jdk Author: JetBrains File: TzdbZoneRulesCompiler.java License: GNU General Public License v2.0 | 6 votes |
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 #4
Source Project: mr4c Author: google File: CustomFormat.java License: Apache License 2.0 | 6 votes |
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 #5
Source Project: cloud-odata-java Author: SAP File: BatchResponseParser.java License: Apache License 2.0 | 6 votes |
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 #6
Source Project: jdk8u60 Author: chenghanpeng File: TzdbZoneRulesCompiler.java License: GNU General Public License v2.0 | 6 votes |
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 Project: nextreports-designer Author: nextreports File: FindReplaceDialog.java License: Apache License 2.0 | 6 votes |
/** * 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 #8
Source Project: tilt-game-android Author: mediamonks File: SystemUtils.java License: MIT License | 6 votes |
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 #9
Source Project: hottub Author: dsrg-uoft File: TzdbZoneRulesCompiler.java License: GNU General Public License v2.0 | 6 votes |
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 #10
Source Project: RestServices Author: mendix File: UriTemplate.java License: Apache License 2.0 | 6 votes |
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 #11
Source Project: liiklus Author: bsideup File: GroupId.java License: MIT License | 6 votes |
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 #12
Source Project: nexus-public Author: sonatype File: RegexMatcher.java License: Eclipse Public License 1.0 | 6 votes |
@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 #13
Source Project: sinavi-jfw Author: ctc-g File: Strings.java License: Apache License 2.0 | 6 votes |
/** * 引数の文字列をラクダ記法(単語区切りが大文字)とみなして、 * それを全て大文字のスネーク記法(単語区切りがアンダースコア)に変換します。 * 例えば、ラクダ記法の<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 #14
Source Project: openjdk-jdk8u Author: AdoptOpenJDK File: TzdbZoneRulesCompiler.java License: GNU General Public License v2.0 | 6 votes |
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 #15
Source Project: openjdk-jdk8u-backup Author: AdoptOpenJDK File: TzdbZoneRulesCompiler.java License: GNU General Public License v2.0 | 6 votes |
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 #16
Source Project: Pydev Author: fabioz File: PercentToBraceConverter.java License: Eclipse Public License 1.0 | 6 votes |
/** * 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 #17
Source Project: styx Author: HotelsDotCom File: RewriteConfig.java License: Apache License 2.0 | 6 votes |
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 #18
Source Project: openjdk-jdk9 Author: AdoptOpenJDK File: DefaultFormat.java License: GNU General Public License v2.0 | 6 votes |
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 #19
Source Project: openjdk-jdk9 Author: AdoptOpenJDK File: DefaultFormat.java License: GNU General Public License v2.0 | 6 votes |
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 #20
Source Project: thym Author: eclipse File: PluginMessagesCLIResult.java License: Eclipse Public License 1.0 | 6 votes |
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 Project: jdk8u-jdk Author: lambdalab-mirror File: TzdbZoneRulesCompiler.java License: GNU General Public License v2.0 | 6 votes |
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 #22
Source Project: es6draft Author: anba File: RegExpPrototype.java License: MIT License | 6 votes |
/** * 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 #23
Source Project: CogStack-Pipeline Author: CogStack File: ElasticGazetteerAcceptanceTest.java License: Apache License 2.0 | 6 votes |
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 #24
Source Project: CostFed Author: dice-group File: QueryManager.java License: GNU Affero General Public License v3.0 | 6 votes |
/** * 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 #25
Source Project: FreeBuilder Author: inferred File: TypeMirrors.java License: Apache License 2.0 | 5 votes |
/** Replaces the given match with the given replacement string. */ void replace(MatchResult match, String replacement) { Preconditions.checkArgument( match.group().equals(value.substring(match.start(), match.end())), "MatchResult does not match the current value of this string"); value = value.substring(0, match.start()) + replacement + value.substring(match.end()); }
Example #26
Source Project: java-repl Author: albertlatacz File: Evaluator.java License: Apache License 2.0 | 5 votes |
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)); } }
Example #27
Source Project: nextreports-designer Author: nextreports File: FindReplaceDialog.java License: Apache License 2.0 | 5 votes |
private MatchResult getMatchResult(Matcher matcher, boolean onlyFirst) { MatchResult matchResult = null; while (matcher.find()) { matchResult = matcher.toMatchResult(); if (onlyFirst) { break; } } return matchResult; }
Example #28
Source Project: common-utils Author: knightliao File: MatchResultSubstitution.java License: GNU General Public License v2.0 | 5 votes |
@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 Project: riposte Author: Nike-Inc File: Parser.java License: Apache License 2.0 | 5 votes |
public MatchResult parse(final ParserInput parserInput) throws ParserFailure { final Matcher matcher = pattern.matcher( parserInput.getText().subSequence(parserInput.getOffset(), parserInput.getText().length()) ); if (matcher.lookingAt()) { parserInput.setOffset(parserInput.getOffset() + matcher.end()); return matcher.toMatchResult(); } else { throw new ParserFailure("Regular Expression parser with pattern '" + pattern.pattern() + "' did not match the input text ( using matcher.lookingAt() )", parserInput); } }
Example #30
Source Project: tilt-game-android Author: mediamonks File: SystemUtils.java License: MIT License | 5 votes |
public static float getCPUBogoMips() throws SystemUtilsException { final MatchResult matchResult = SystemUtils.matchSystemFile("/proc/cpuinfo", SystemUtils.BOGOMIPS_PATTERN, 1000); try { if (matchResult.groupCount() > 0) { return Float.parseFloat(matchResult.group(1)); } else { throw new SystemUtilsException(); } } catch (final NumberFormatException e) { throw new SystemUtilsException(e); } }