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()); }
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; }
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; }
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"); } } } }
/** * 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)); } } }
/** * 根据文件名得到插件名 * * @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); }
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; }
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; }
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(); }
@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(); }
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()); } } }
@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]; }
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()); } }; }
/** * 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; }
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(); }
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; } }); }
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(); }
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; }
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; }
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); }
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; }
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(); }
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(); }
/** * 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; }
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(); }
/** * 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; }
/** * 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()); }
/** * 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); }
/** * 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)); } } }
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; }
@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; }
@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); }
@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; }
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); }
@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; }