Java Code Examples for java.util.regex.Matcher#reset()

The following examples show how to use java.util.regex.Matcher#reset() . 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: LogsParser.java    From Varis-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Turns a single TextLeaf with any number of travis_fold:... or travis_time:... commands into
 * multiple LogEntryComponents ensuring that each command has its own TravisCommandLeaf.
 */
private List<LogEntryComponent> splitAtTravisCommands(TextLeaf textLeaf) {
    List<LogEntryComponent> result = new ArrayList<>();
    Matcher matcher = TRAVIS_COMMAND.matcher(textLeaf.getText());
    while (matcher.find()) {
        // Create a new node for the part before the travis command (if non-empty)
        if (matcher.start() > 0) {
            TextLeaf splitFront = new TextLeaf(textLeaf.getOptions());
            splitFront.setText(textLeaf.getText().substring(0, matcher.start()));
            result.add(splitFront);
        }

        // Create a node for the command
        result.add(new TravisCommandLeaf(matcher.group(1), matcher.group(2), matcher.group(3)));

        // Set text to what remains after the command
        textLeaf.setText(textLeaf.getText().substring(matcher.end()));
        matcher.reset(textLeaf.getText());
    }
    result.add(textLeaf);
    return result;
}
 
Example 2
Source File: DateFormatUtils.java    From logsniffer with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void replace(final Pattern searchPattern, final String[]... alternatives) {
	final Matcher matcher = searchPattern.matcher(pattern.toString());
	if (matcher.matches()) {
		final StringBuilder rplStr = new StringBuilder("(");
		for (final String[] pool : alternatives) {
			for (final String s : pool) {
				if (rplStr.length() > 1) {
					rplStr.append("|");
				}
				rplStr.append(Pattern.quote(s));
			}
		}
		rplStr.append(")");
		int dif = 0;
		matcher.reset();
		while (matcher.find()) {
			dif += -(pattern.length() - pattern
					.replace(matcher.start() + dif, matcher.end() + dif, "@" + replacedParts.size() + "@")
					.length());
			replacedParts.add(rplStr.toString());
		}
	}
}
 
Example 3
Source File: RelaxedNames.java    From spring-cloud-deployer-kubernetes with Apache License 2.0 6 votes vote down vote up
@Override
public String apply(String value) {
	if (value.isEmpty()) {
		return value;
	}
	Matcher matcher = CAMEL_CASE_PATTERN.matcher(value);
	if (!matcher.find()) {
		return value;
	}
	matcher = matcher.reset();
	StringBuffer result = new StringBuffer();
	while (matcher.find()) {
		matcher.appendReplacement(result, matcher.group(1) + '-'
				+ StringUtils.uncapitalize(matcher.group(2)));
	}
	matcher.appendTail(result);
	return result.toString();
}
 
Example 4
Source File: Arglets.java    From cmake4eclipse with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * @param cwd
 *          the current working directory of the compiler at its invocation
 * @see de.marw.cmake.cdt.lsp.IArglet#processArgument(IParseContext, IPath, String)
 */
protected final int processArgument(IParseContext parseContext, IPath cwd,
    String argsLine, NameOptionMatcher[] optionMatchers) {
  for (NameOptionMatcher oMatcher : optionMatchers) {
    final Matcher matcher = oMatcher.matcher;

    matcher.reset(argsLine);
    if (matcher.lookingAt()) {
      String name = matcher.group(oMatcher.nameGroup);
      IPath path = Path.fromOSString(name);
      if (!path.isAbsolute()) {
        // prepend CWD
        name = cwd.append(path).toOSString();
      }

      final ICLanguageSettingEntry entry = CDataUtil.createCMacroFileEntry(name,
          ICSettingEntry.READONLY);
      parseContext.addSettingEntry(entry);
      final int end = matcher.end();
      return end;
    }
  }
  return 0;// no input consumed
}
 
Example 5
Source File: ProtocolGenericBindingProvider.java    From openhab1-addons with Eclipse Public License 2.0 6 votes vote down vote up
private void parseAndAddBindingConfig(Item item, String bindingConfig) throws BindingConfigParseException {
    ProtocolBindingConfig newConfig = new ProtocolBindingConfig();
    Matcher matcher = BASE_CONFIG_PATTERN.matcher(bindingConfig);

    if (!matcher.matches()) {
        throw new BindingConfigParseException(
                "bindingConfig '" + bindingConfig + "' doesn't contain a valid binding configuration");
    }
    matcher.reset();

    while (matcher.find()) {
        String bindingConfigPart = matcher.group(1);
        if (StringUtils.isNotBlank(bindingConfigPart)) {
            parseBindingConfig(newConfig, item, bindingConfigPart);
            addBindingConfig(item, newConfig);
        }
    }
}
 
Example 6
Source File: RelaxedNames.java    From spring-cloud-dataflow with Apache License 2.0 6 votes vote down vote up
@Override
public String apply(String value) {
	if (value.isEmpty()) {
		return value;
	}
	Matcher matcher = CAMEL_CASE_PATTERN.matcher(value);
	if (!matcher.find()) {
		return value;
	}
	matcher = matcher.reset();
	StringBuffer result = new StringBuffer();
	while (matcher.find()) {
		matcher.appendReplacement(result, matcher.group(1) + '-'
				+ StringUtils.uncapitalize(matcher.group(2)));
	}
	matcher.appendTail(result);
	return result.toString();
}
 
Example 7
Source File: StringRedactor.java    From datacollector with Apache License 2.0 6 votes vote down vote up
/**
 * The actual work of redaction.
 * @param msg The string to redact
 * @return If any redaction was performed, the redacted string. Otherwise
 *         the original is returned.
 */
private String redact(String msg) {
  if (msg == null) {
    return null;
  }
  String original = msg;
  boolean matched = false;
  for (RedactionRule rule : rules) {
    if (rule.matchesTrigger(msg)) {
      Matcher m = rule.matcherTL.get();
      m.reset(msg);
      if (m.find()) {
        msg = m.replaceAll(rule.replace);
        matched = true;
      }
    }
  }
  return matched ? msg : original;
}
 
Example 8
Source File: SexpHandler.java    From e4macs with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * If a _ is not a word break character, see if the BreakIterator stopped on one
 * 
 * @param doc
 * @param pos
 * @return new offset if word moves past any _'s, else pos
 */
int checkUnder(IDocument doc, int pos) {
	int result = pos;
	try {
		if (!isUnder()) {
			char c = doc.getChar(pos);
			if (!isDot() || c != '.') {
				IRegion lineInfo = doc.getLineInformationOfOffset(pos);
				int p = pos;
				// if we're at or just moved over an _
				if (c == '_' || (--p >= lineInfo.getOffset() && doc.getChar(p) == '_')) {
					int end = (lineInfo.getOffset() + lineInfo.getLength()); 
					if (end > p) {
						Matcher matcher = getUnderMatcher();
						matcher.reset(doc.get(p, end - p));
						if (matcher.matches()) {
							result = p + matcher.end(1);
						}
					}
				}
			}
		}
	} catch (BadLocationException e) {
	}
	return result;
}
 
Example 9
Source File: RegEx.java    From ranger with Apache License 2.0 6 votes vote down vote up
protected void populateReplacementPatterns(String baseProperty, List<String> regexPatterns) throws Throwable{
	replacementPattern = new LinkedHashMap<String, String>();
	Pattern p = Pattern.compile("s/([^/]*)/([^/]*)/(g)?");
	for (String regexPattern : regexPatterns) {
		Matcher m = p.matcher(regexPattern);
		if (!m.matches()) {
			logger.warn("Invalid RegEx " + regexPattern + " and hence skipping this regex property");
		}
		m = m.reset();
		while (m.find()) {
			String matchPattern = m.group(1);
			String replacement = m.group(2);
			if (matchPattern != null && !matchPattern.isEmpty() && replacement != null) {
				replacementPattern.put(matchPattern, replacement);
				if (logger.isDebugEnabled()) {
					logger.debug(baseProperty + " match pattern = " + matchPattern + " and replacement string = " + replacement);
				}
			}
		}
	}
}
 
Example 10
Source File: ExecGenericBindingProvider.java    From openhab1-addons with Eclipse Public License 2.0 6 votes vote down vote up
protected ExecBindingConfig parseInBindingConfig(Item item, String bindingConfig, ExecBindingConfig config)
        throws BindingConfigParseException {

    Matcher matcher = IN_BINDING_PATTERN.matcher(bindingConfig);

    if (!matcher.matches()) {
        throw new BindingConfigParseException(
                "bindingConfig '" + bindingConfig + "' doesn't represent a valid in-binding-configuration.");
    }
    matcher.reset();

    ExecBindingConfigElement configElement;

    while (matcher.find()) {
        configElement = new ExecBindingConfigElement();
        configElement.commandLine = matcher.group(1).replaceAll("\\\\\"", "");
        configElement.refreshInterval = Integer.valueOf(matcher.group(2)).intValue();
        configElement.transformation = matcher.group(3).replaceAll("\\\\\"", "\"");
        config.put(IN_BINDING_KEY, configElement);
    }

    return config;
}
 
Example 11
Source File: TextQueryExecutor.java    From scriptella-etl with Apache License 2.0 5 votes vote down vote up
/**
 * Executes a query and iterates the resultset using the callback.
 *
 * @param qc      callback to notify on each row.
 * @param counter statements counter.
 */
public void execute(Reader reader, final QueryCallback qc, AbstractConnection.StatementCounter counter) {
    int qCount = query.length;
    Matcher[] matchers = new Matcher[qCount];

    LineIterator it = new LineIterator(reader, ps, textParams.isTrimLines());
    //Skip a specified number of lines
    for (int i = textParams.getSkipLines(); i > 0  && it.hasNext(); i--) {
        it.next();
    }
    while (it.hasNext()) {
        String line = it.next();
        for (int i = 0; i < qCount; i++) {
            Matcher m = matchers[i];
            if (m == null) { //First time initialization
                m = query[i].matcher(line);
                matchers[i] = m;
            } else { //Reuse matcher for better performance
                m.reset(line);
            }
            if (m.find()) {
                if (LOG.isLoggable(Level.FINE)) {
                    LOG.info("Pattern matched: " + m);
                }
                result = m;
                qc.processRow(this);
            }
        }
    }
    counter.statements += qCount;
}
 
Example 12
Source File: Window.java    From YetAnotherPixelDungeon with GNU General Public License v3.0 5 votes vote down vote up
public Highlighter( String text ) {
	
	String stripped = STRIPPER.matcher( text ).replaceAll( "" );
	mask = new boolean[stripped.length()];
	
	Matcher m = HIGHLIGHTER.matcher( stripped );
	
	int pos = 0;
	int lastMatch = 0;
	
	while (m.find()) {
		pos += (m.start() - lastMatch);
		int groupLen = m.group( 1 ).length();
		for (int i=pos; i < pos + groupLen; i++) {
			mask[i] = true;
		}
		pos += groupLen;
		lastMatch = m.end();
	}
	
	m.reset( text );
	StringBuffer sb = new StringBuffer();
	while (m.find()) {
		m.appendReplacement( sb, m.group( 1 ) );
	}
	m.appendTail( sb );
	
	this.text = sb.toString();
}
 
Example 13
Source File: ExtractPattern.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
public static Match extract(Matcher matcher, String matchee, IndexType type, int index) {
  matcher.reset(matchee);
  switch (type) {
    case INDEX:
    case INDEX_BACKWARDS:
      List<Match> matches = new ArrayList<Match>();
      while (matcher.find()) {
        matches.add(PatternMatchUtils.match(matcher));
      }
      int length = matches.size();
      int i = (type == INDEX_BACKWARDS) ? length - 1 - index : index;
      if (i < matches.size() && i >= 0) {
        return matches.get(i);
      }
      break;
    case CAPTURE_GROUP:
      if (matcher.matches()) {
        if (index >= 0 && index < matcher.groupCount()) {
          return PatternMatchUtils.groupMatch(matcher, index);
        }
      }
      break;
    default:
      throw new UnsupportedOperationException(type.name());
  }
  return null;
}
 
Example 14
Source File: HtmlUtil.java    From TLint with Apache License 2.0 5 votes vote down vote up
public static String transImgToLocal(String content) {
    Pattern pattern = Pattern.compile("<img(.+?)data_url=\"(.+?)\"(.+?)src=\"(.+?)\"(.+?)>");
    Matcher localMatcher = pattern.matcher(content);
    while (localMatcher.find()) {
        String imageUrl = localMatcher.group(4);
        String localUrl = transToLocal(imageUrl);
        String localPath = "file://" + ConfigUtil.getCachePath() + File.separator + localUrl;
        if (FileUtil.exist(localPath)) {
            content = content.replace(imageUrl, localUrl);
        }
    }
    localMatcher.reset();
    return content;
}
 
Example 15
Source File: HeapHistoBeanHandle.java    From bistoury with GNU General Public License v3.0 5 votes vote down vote up
private HistogramBean parseHistogramBean(Matcher matcher, String line) {
    matcher.reset(line);
    if (matcher.matches()) {
        return new HistogramBean(matcher.group(COUNT_INDEX), matcher.group(BYTES_INDEX), matcher.group(CLASSNAME_INDEX));
    }
    return null;
}
 
Example 16
Source File: CCModel.java    From CodeChickenLib with GNU Lesser General Public License v2.1 4 votes vote down vote up
public static void assertMatch(Matcher m, String s)
{
    m.reset(s);
    illegalAssert(m.matches(), "Malformed line: "+s);
}
 
Example 17
Source File: HttpGenericBindingProvider.java    From openhab1-addons with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Parses an http-out configuration by using the regular expression
 * <code>(.*?):([A-Z]*):(.*)</code>. Where the groups should contain the
 * following content:
 * <ul>
 * <li>1 - command</li>
 * <li>2 - http method</li>
 * <li>3 - url</li>
 * <li>4 - post body</li>
 * </ul>
 *
 * @param item
 * @param bindingConfig the config string to parse
 * @param config
 * @return the filled {@link HttpBindingConfig}
 *
 * @throws BindingConfigParseException if the regular expression doesn't match
 *             the given <code>bindingConfig</code>
 */
protected HttpBindingConfig parseOutBindingConfig(Item item, String bindingConfig, HttpBindingConfig config)
        throws BindingConfigParseException {
    logger.debug("parsing this as an http out binding: {}", bindingConfig);
    Matcher matcher = OUT_BINDING_PATTERN.matcher(bindingConfig);

    if (!matcher.matches()) {
        throw new BindingConfigParseException("bindingConfig '" + bindingConfig
                + "' doesn't contain a valid out-binding-configuration. A valid configuration is matched by the RegExp '"
                + OUT_BINDING_PATTERN + "'");
    }
    matcher.reset();

    HttpBindingConfigElement configElement;

    while (matcher.find()) {
        configElement = new HttpBindingConfigElement();

        Command command = createCommandFromString(item, matcher.group(1));
        configElement.httpMethod = matcher.group(2);
        String lastPart = matcher.group(3).replaceAll("\\\\\"", "");
        logger.debug("URL portion of binding config to be processed: {}", lastPart);

        Matcher urlMatcher = URL_PARSING_PATTERN.matcher(lastPart);
        urlMatcher.find();
        if (logger.isDebugEnabled()) {
            for (int i = 0; i <= urlMatcher.groupCount(); i++) {
                logger.debug("Group {}: {}", i, urlMatcher.group(i));
            }
        }

        if (urlMatcher.group(1).endsWith("}")) {
            String g1 = urlMatcher.group(1);
            int beginIdx = g1.indexOf("{");
            int endIdx = g1.indexOf("}");
            configElement.url = g1.substring(0, beginIdx);
            configElement.headers = parseHttpHeaders(g1.substring(beginIdx + 1, endIdx));
        } else {
            configElement.url = urlMatcher.group(1);
        }

        if (configElement.httpMethod.equals("POST") && urlMatcher.group(11) != null) {
            configElement.body = urlMatcher.group(11).substring(1);
            setBodyTransform(configElement, command);
        }

        config.put(command, configElement);
    }

    return config;
}
 
Example 18
Source File: ExecGenericBindingProvider.java    From openhab1-addons with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void processBindingConfiguration(String context, Item item, String bindingConfig)
        throws BindingConfigParseException {

    super.processBindingConfiguration(context, item, bindingConfig);

    ExecBindingConfig config = new ExecBindingConfig();
    config.acceptedDataTypes = new ArrayList<Class<? extends State>>(item.getAcceptedDataTypes());

    Matcher matcher = BASE_CONFIG_PATTERN.matcher(bindingConfig);

    if (!matcher.matches()) {

        if (bindingConfig.startsWith("<") || bindingConfig.startsWith(">")) {
            throw new BindingConfigParseException("Exec binding legacy format cannot start with '<' or '>' ");
        }

        // backward compatibility for old format
        parseLegacyOutBindingConfig(item, bindingConfig, config);

    } else {

        matcher.reset();

        while (matcher.find()) {
            String direction = matcher.group(1);
            String bindingConfigPart = matcher.group(2);

            if (direction.equals("<")) {
                config = parseInBindingConfig(item, bindingConfigPart, config);
            } else if (direction.equals(">")) {
                config = parseOutBindingConfig(item, bindingConfigPart, config);
            } else {
                throw new BindingConfigParseException(
                        "Unknown command given! Configuration must start with '<' or '>' ");
            }
        }
    }

    addBindingConfig(item, config);

}
 
Example 19
Source File: DescriptionFieldAdapter.java    From opentasks with Apache License 2.0 4 votes vote down vote up
private static List<DescriptionItem> parseDescription(String description)
{
    List<DescriptionItem> result = new ArrayList<DescriptionItem>(16);
    if (TextUtils.isEmpty(description))
    {
        return result;
    }
    Matcher matcher = CHECKMARK_PATTERN.matcher("");
    StringBuilder currentParagraph = new StringBuilder();
    boolean currentHasCheckedMark = false;
    boolean currentIsChecked = false;
    for (String line : description.split("\n"))
    {
        matcher.reset(line);

        if (matcher.lookingAt())
        {
            // start a new paragraph, if we already had one
            if (currentParagraph.length() > 0)
            {
                result.add(new DescriptionItem(currentHasCheckedMark, currentIsChecked,
                        currentHasCheckedMark ? currentParagraph.toString().trim() : currentParagraph.toString()));
            }
            currentHasCheckedMark = true;
            currentIsChecked = "x".equals(matcher.group(2).toLowerCase());
            currentParagraph.setLength(0);
            currentParagraph.append(matcher.group(3));
        }
        else
        {
            if (currentHasCheckedMark)
            {
                // start a new paragraph, if the last one had a tick mark
                if (currentParagraph.length() > 0)
                {
                    // close last paragraph
                    result.add(new DescriptionItem(currentHasCheckedMark, currentIsChecked, currentParagraph.toString().trim()));
                }
                currentHasCheckedMark = false;
                currentParagraph.setLength(0);
            }
            if (currentParagraph.length() > 0)
            {
                currentParagraph.append("\n");
            }
            currentParagraph.append(line);
        }
    }

    // close paragraph
    if (currentHasCheckedMark || currentParagraph.length() > 0)
    {
        result.add(new DescriptionItem(currentHasCheckedMark, currentIsChecked,
                currentHasCheckedMark ? currentParagraph.toString().trim() : currentParagraph.toString()));
    }
    return result;
}
 
Example 20
Source File: SpoofCheckerTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
@Test
public void testConfData() {
    if (TestUtil.getJavaVendor() == JavaVendor.IBM && TestUtil.getJavaVersion() == 5) {
        // Note: IBM Java 5 has a bug reading a large UTF-8 text contents
        logln("Skip this test case because of the IBM Java 5 bug");
        return;
    }
    try {
        // Read in the confusables.txt file. (Distributed by Unicode.org)
        String fileName = "unicode/confusables.txt";
        BufferedReader confusablesRdr = TestUtil.getDataReader(fileName, "UTF-8");

        // Create a default spoof checker to use in this test.
        SpoofChecker sc = new SpoofChecker.Builder().build();

        // Parse lines from the confusables.txt file. Example Line:
        // FF44 ; 0064 ; SL # ( d -> d ) FULLWIDTH ....
        // Lines have three fields. The hex fields can contain more than one character,
        // and each character may be more than 4 digits (for supplemntals)
        // This regular expression matches lines and splits the fields into capture groups.
        // Capture group 1: map from chars
        // 2: map to chars
        // 3: table type, SL, ML, SA or MA (deprecated)
        // 4: Comment Lines Only
        // 5: Error Lines Only
        Matcher parseLine = Pattern.compile(
                "\\ufeff?" + "(?:([0-9A-F\\s]+);([0-9A-F\\s]+);\\s*(SL|ML|SA|MA)\\s*(?:#.*?)?$)"
                        + "|\\ufeff?(\\s*(?:#.*)?)"). // Comment line
                        matcher("");
        Normalizer2 normalizer = Normalizer2.getNFDInstance();
        int lineNum = 0;
        String inputLine;
        while ((inputLine = confusablesRdr.readLine()) != null) {
            lineNum++;
            parseLine.reset(inputLine);
            if (!parseLine.matches()) {
                errln("Syntax error in confusable data file at line " + lineNum);
                errln(inputLine);
                break;
            }
            if (parseLine.group(4) != null) {
                continue; // comment line
            }
            String from = parseHex(parseLine.group(1));

            if (!normalizer.isNormalized(from)) {
                // The source character was not NFD.
                // Skip this case; the first step in obtaining a skeleton is to NFD the input,
                // so the mapping in this line of confusables.txt will never be applied.
                continue;
            }

            String rawExpected = parseHex(parseLine.group(2));
            String expected = normalizer.normalize(rawExpected);

            String actual;
            actual = sc.getSkeleton(from);

            if (!actual.equals(expected)) {
                errln("confusables.txt: " + lineNum + ": " + parseLine.group(0));
                errln("Actual: " + escapeString(actual));
            }
        }
        confusablesRdr.close();
    } catch (IOException e) {
        errln(e.toString());
    }
}