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

The following examples show how to use java.util.regex.Matcher#appendReplacement() . 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: LevelDBImport.java    From jane with GNU Lesser General Public License v3.0 6 votes vote down vote up
private static Octets str2Oct(String str)
{
	String matchStr = "";
	try
	{
		Matcher mat = s_patHex.matcher(str);
		if (!mat.find())
			return Octets.wrap(str.getBytes(s_cs88591));
		StringBuilder sb = new StringBuilder(str.length());
		do
		{
			matchStr = mat.group(1);
			mat.appendReplacement(sb, Matcher.quoteReplacement(String.valueOf((char)(Integer.parseInt(matchStr, 16)))));
		}
		while (mat.find());
		return Octets.wrap(mat.appendTail(sb).toString().getBytes(s_cs88591));
	}
	catch (RuntimeException e)
	{
		System.err.println("ERROR: parse failed: '" + matchStr + "' in '" + str + '\'');
		throw e;
	}
}
 
Example 2
Source File: ReplaceRefactoring.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
private String computeReplacementString(Pattern pattern, String originalText, String replacementText,
        String lineDelimiter) throws PatternSyntaxException {
    if (pattern != null) {
        try {
            replacementText = PatternConstructor.interpretReplaceEscapes(replacementText, originalText,
                    lineDelimiter);

            Matcher matcher = pattern.matcher(originalText);
            StringBuffer sb = new StringBuffer();
            matcher.reset();
            if (matcher.find()) {
                matcher.appendReplacement(sb, replacementText);
            } else {
                return null;
            }
            matcher.appendTail(sb);
            return sb.toString();
        } catch (IndexOutOfBoundsException ex) {
            throw new PatternSyntaxException(ex.getLocalizedMessage(), replacementText, -1);
        }
    }
    return replacementText;
}
 
Example 3
Source File: Transformations.java    From AliceBot with Apache License 2.0 6 votes vote down vote up
private String substitute(String input, Mapper mapper) {
	StringBuffer buffer = new StringBuffer();
	for (String find : correction.keySet()) {
		Pattern pattern = Pattern.compile(find, CASE_INSENSITIVE
				| UNICODE_CASE);
		Matcher matcher = pattern.matcher(input);
		String replace = correction.get(find);

		mapper.prepare(input, find, replace);
		while (!matcher.hitEnd() && matcher.find()) {
			mapper.update(matcher.start() + 1);
			matcher.appendReplacement(buffer, replace);
		}

		matcher.appendTail(buffer);
		input = buffer.toString();
		buffer.delete(0, buffer.length());
	}

	return input;
}
 
Example 4
Source File: ParseUtils.java    From dubbox with Apache License 2.0 6 votes vote down vote up
/**
 * 执行interpolation(变量插入)。
 * 
 * @param expression 含有变量的表达式字符串。表达式中的变量名也可以用<code>{}</code>括起来。
 * @param params 变量集。变量名可以包含<code>.</code>、<code>_</code>字符。
 * @return 完成interpolation后的字符串。 如:<code><pre>xxx${name}zzz -> xxxjerryzzz</pre></code>(其中变量name="jerry")
 * @throws IllegalStateException 表达式字符串中使用到的变量 在变量集中没有
 */
// FIMXE 抛出IllegalStateException异常,是否合适?!
public static String interpolate(String expression, Map<String, String> params) {
    if (expression == null || expression.length() == 0) {
        throw new IllegalArgumentException("glob pattern is empty!");
    }
    if (expression.indexOf('$') < 0) {
        return expression;
    }
    Matcher matcher = VARIABLE_PATTERN.matcher(expression);
    StringBuffer sb = new StringBuffer();
    while (matcher.find()) { // 逐个匹配
        String key = matcher.group(1);
        String value = params == null ? null: params.get(key);
        if (value == null) {
        	value = "";
        }
        matcher.appendReplacement(sb, value);
    }
    matcher.appendTail(sb);
    return sb.toString();
}
 
Example 5
Source File: Stash.java    From crate with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves a value from the current stash.
 * The stash contains fields eventually extracted from previous responses that can be reused
 * as arguments for following requests (e.g. scroll_id)
 */
public Object getValue(String key) throws IOException {
    if (key.charAt(0) == '$' && key.charAt(1) != '{') {
        return unstash(key.substring(1));
    }
    Matcher matcher = EXTENDED_KEY.matcher(key);
    /*
     * String*Buffer* because that is what the Matcher API takes. In modern versions of java the uncontended synchronization is very,
     * very cheap so that should not be a problem.
     */
    StringBuffer result = new StringBuffer(key.length());
    if (false == matcher.find()) {
        throw new IllegalArgumentException("Doesn't contain any stash keys [" + key + "]");
    }
    do {
        matcher.appendReplacement(result, Matcher.quoteReplacement(unstash(matcher.group(1)).toString()));
    } while (matcher.find());
    matcher.appendTail(result);
    return result.toString();
}
 
Example 6
Source File: KmlUtil.java    From android-maps-utils with Apache License 2.0 5 votes vote down vote up
/**
 * Substitute property values in BalloonStyle text template
 *
 * @param template text template
 * @param placemark placemark to get property values from
 * @return string with property values substituted
 */
public static String substituteProperties(String template, KmlPlacemark placemark) {
    StringBuffer sb = new StringBuffer();
    Pattern pattern = Pattern.compile("\\$\\[(.+?)]");
    Matcher matcher = pattern.matcher(template);
    while (matcher.find()) {
        String property = matcher.group(1);
        String value = placemark.getProperty(property);
        if (value != null) {
            matcher.appendReplacement(sb, value);
        }
    }
    matcher.appendTail(sb);
    return sb.toString();
}
 
Example 7
Source File: Inflector.java    From usergrid with Apache License 2.0 5 votes vote down vote up
/**
 * Utility method to replace all occurrences given by the specific backreference with its uppercased form, and
 * remove all other backreferences. <p> The Java {@link Pattern regular expression processing} does not use the
 * preprocessing directives <code>\l</code>, <code>&#92;u</code>, <code>\L</code>, and <code>\U</code>. If so, such
 * directives could be used in the replacement string to uppercase or lowercase the backreferences. For example,
 * <code>\L1</code> would lowercase the first backreference, and <code>&#92;u3</code> would uppercase the 3rd
 * backreference. </p>
 *
 * @return the input string with the appropriate characters converted to upper-case
 */
protected static String replaceAllWithUppercase( String input, String regex, int groupNumberToUppercase ) {
    Pattern underscoreAndDotPattern = Pattern.compile( regex );
    Matcher matcher = underscoreAndDotPattern.matcher( input );
    StringBuffer sb = new StringBuffer();
    while ( matcher.find() ) {
        matcher.appendReplacement( sb, matcher.group( groupNumberToUppercase ).toUpperCase() );
    }
    matcher.appendTail( sb );
    return sb.toString();
}
 
Example 8
Source File: HtmlUtil.java    From PowerFileExplorer with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Xóa nội dung của String defStr theo Pattern pat
 * @param defStr
 * @param pat
 * @return
 */
public static StringBuffer removePatternContents(String defStr, Pattern pat) {
	Matcher mat = pat.matcher(defStr);
	StringBuffer sb = new StringBuffer();
	while (mat.find()) {
		mat.appendReplacement(sb, " ");
	}
	mat.appendTail(sb);
	return sb;
}
 
Example 9
Source File: StringUtil.java    From feiqu-opensource with Apache License 2.0 5 votes vote down vote up
/**
 * 驼峰转下划线,效率比上面高
 * @param str
 * @return
 */
public static String humpToLine2(String str) {
    Matcher matcher = humpPattern.matcher(str);
    StringBuffer sb = new StringBuffer();
    while (matcher.find()) {
        matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
    }
    matcher.appendTail(sb);
    return sb.toString();
}
 
Example 10
Source File: HexString.java    From zap-extensions with Apache License 2.0 5 votes vote down vote up
static String compile(String binaryRegex) {
    Matcher matcher = HEX_VALUE.matcher(binaryRegex);
    StringBuffer sb = new StringBuffer();
    while (matcher.find()) {
        String value = matcher.group();
        if (!value.startsWith(ESCAPED_ESCAPE_CHAR)) {
            value = convertByte(value.substring(2));
        }
        matcher.appendReplacement(sb, value);
    }
    matcher.appendTail(sb);
    return sb.toString();
}
 
Example 11
Source File: Utils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Utility method that finds all occurrences of variable references and
 * replaces them with their values.
 * Values are taken from <code>varMap</code> and escaped. If they are
 * not present there, system properties are queried. If not found there
 * the variable reference is replaced with the same string with special
 * characters escaped.
 * 
 * @param value String value where the variables have to be replaced with values
 * @param varMap mapping of variable names to their values
 * @return String where the all the replacement was done
 */
public static String doSub(String value, Map<String, String> varMap) {
    try {
        Matcher matcher = pattern.matcher(value);
        boolean result = matcher.find();
        if (result) {
            StringBuffer sb = new StringBuffer(value.length() * 2);
            do {
                String key = matcher.group(1);
                String replacement = varMap.get(key);
                if (replacement == null) {
                    replacement = System.getProperty(key);
                    if (replacement != null) {
                        replacement = escapePath(replacement);
                    } else {
                        replacement = "\\$\\{" + key + "\\}"; // NOI18N
                    }
                } else {
                    replacement = escapePath(replacement);
                }
                matcher.appendReplacement(sb, replacement);
                result = matcher.find();
            } while (result);
            matcher.appendTail(sb);
            value = sb.toString();
        }
    } catch (Exception ex) {
        Logger.getLogger("glassfish").log(Level.INFO, ex.getLocalizedMessage(), ex); // NOI18N
    }
    return value;
}
 
Example 12
Source File: AbstractQueryMacroHandler.java    From cuba with Apache License 2.0 5 votes vote down vote up
@Override
public String expandMacro(String queryString) {
    count = 0;
    Matcher matcher = macroPattern.matcher(queryString);
    StringBuffer sb = new StringBuffer();
    while (matcher.find()) {
        matcher.appendReplacement(sb, doExpand(matcher.group(1)));
    }
    matcher.appendTail(sb);
    return sb.toString();
}
 
Example 13
Source File: NacosConfigProperties.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
private String resolveKey(String key) {
	Matcher matcher = PATTERN.matcher(key);
	StringBuffer sb = new StringBuffer();
	while (matcher.find()) {
		matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
	}
	matcher.appendTail(sb);
	return sb.toString();
}
 
Example 14
Source File: CodecUtils.java    From enkan with Eclipse Public License 1.0 5 votes vote down vote up
public static String urlDecode(String encoded, String encoding) {
    try {
        Matcher m = RE_URL_ENCODED_CHARS.matcher(encoded);
        StringBuffer sb = new StringBuffer(encoded.length());
        while (m.find()) {
            String chars = m.group(0);
            m.appendReplacement(sb, new String(parseBytes(chars), encoding));
        }
        m.appendTail(sb);
        return sb.toString();
    } catch (UnsupportedEncodingException e) {
        throw new MisconfigurationException("core.UNSUPPORTED_ENCODING", encoding, e);
    }
}
 
Example 15
Source File: Reflection.java    From LagMonitor with MIT License 5 votes vote down vote up
/**
 * Expand variables such as "{nms}" and "{obc}" to their corresponding packages.
 *
 * @param name - the full name of the class.
 * @return The expanded string.
 */
private static String expandVariables(String name) {
    StringBuffer output = new StringBuffer();
    Matcher matcher = MATCH_VARIABLE.matcher(name);

    while (matcher.find()) {
        String variable = matcher.group(1);
        String replacement;

        // Expand all detected variables
        if ("nms".equalsIgnoreCase(variable)) {
            replacement = NMS_PREFIX;
        } else if ("obc".equalsIgnoreCase(variable)) {
            replacement = OBC_PREFIX;
        } else if ("version".equalsIgnoreCase(variable)) {
            replacement = VERSION;
        } else {
            throw new IllegalArgumentException("Unknown variable: " + variable);
        }

        // Assume the expanded variables are all packages, and append a dot
        if (!replacement.isEmpty() && matcher.end() < name.length() && name.charAt(matcher.end()) != '.') {
            replacement += ".";
        }
        matcher.appendReplacement(output, Matcher.quoteReplacement(replacement));
    }

    matcher.appendTail(output);
    return output.toString();
}
 
Example 16
Source File: PathFormat.java    From kvf-admin with MIT License 4 votes vote down vote up
public static String parse ( String input ) {
	
	Pattern pattern = Pattern.compile( "\\{([^\\}]+)\\}", Pattern.CASE_INSENSITIVE  );
	Matcher matcher = pattern.matcher(input);
	
	PathFormat.currentDate = new Date();
	
	StringBuffer sb = new StringBuffer();
	
	while ( matcher.find() ) {
		
		matcher.appendReplacement(sb, PathFormat.getString( matcher.group( 1 ) ) );
		
	}
	
	matcher.appendTail(sb);
	
	return sb.toString();
}
 
Example 17
Source File: DateParser.java    From ambiverse-nlu with Apache License 2.0 4 votes vote down vote up
/** Normalizes all dates in a String 
 * Note: If you bugfix something in this version, 
 * please check for applying the same fix at the position change tracking function below */
public static String normalize(CharSequence s, Language language) {

  Pattern monthPattern;
  String[] months = null;
  if (language.equals(Language.ENGLISH)) {
    months = MONTHS_EN;
    monthPattern = monthPatternEn;
  } else if (language.equals(Language.GERMAN)) {
    months = MONTHS_DE;
    monthPattern = monthPatternDe;
  } else if (language.equals(Language.SPANISH)) {
    months = MONTHS_ES;
    monthPattern = monthPatternEs;
  } else if (language.equals(Language.FRENCH)) {
    months = MONTHS_FR;
    monthPattern = monthPatternFr;
  } else if (language.equals(Language.ITALIAN)) {
    months = MONTHS_IT;
    monthPattern = monthPatternIt;
  } else {
    throw new IllegalArgumentException("Unsupported language: " + language);
  }

  // If it does not contain years or months, return it unchanged
  if (!monthPattern.matcher(s).find() && !yearPattern.matcher(s).find()) return (s.toString());

  StringBuffer in = new StringBuffer((int) (s.length() * 1.1));

  // Replace all the months
  Matcher m = monthPattern.matcher(s);
  while (m.find()) {
    int monthNum = D.indexOf(m.group().substring(0, 3), (Object[]) months);
    if (monthNum == -1) monthNum = D.indexOf(m.group().substring(0, 4), (Object[]) months);
    monthNum++; // convert from 0-based to 1-based
    m.appendReplacement(in, "MONTH" + (monthNum / 10) + (monthNum % 10));
  }
  m.appendTail(in);
  StringBuffer out = new StringBuffer((int) (in.length() * 1.1));

  // Apply the patterns
  for (FindReplace p : patterns) {
    m = p.pattern.matcher(in);
    if (m.find()) {
      out.setLength(0);
      do {
        m.appendReplacement(out, p.replacement);
      } while (m.find());
      m.appendTail(out);
      StringBuffer temp = out;
      out = in;
      in = temp;
    }

  }

  m = Pattern.compile("&DEC(\\d++)").matcher(in);
  if (m.find()) {
    out.setLength(0);
    do {
      m.appendReplacement(out, "" + (Integer.parseInt(m.group(1)) - 1));
    } while (m.find());
    m.appendTail(out);
    in = null;
    return (out.toString());
  }
  out = null;
  return (in.toString());
}
 
Example 18
Source File: TutorialFilter.java    From projectforge-webapp with GNU General Public License v3.0 4 votes vote down vote up
public void doFilter(final ServletRequest req, final ServletResponse resp, final FilterChain chain) throws IOException, ServletException
{
  final String uri = ((HttpServletRequest) req).getRequestURI();
  if (uri.matches(".*/ProjectForge.*.html") == false) {
    chain.doFilter(req, resp);
    return;
  }
  final PrintWriter out = resp.getWriter();
  final CharResponseWrapper wrapper = new CharResponseWrapper((HttpServletResponse) resp);
  chain.doFilter(req, wrapper);
  final CharArrayWriter caw = new CharArrayWriter();
  final String tutorialUrl = ((HttpServletResponse) resp).encodeURL(WicketUtils.getAbsoluteUrl("/wa/tutorial"));
  final String regexp = "(\\{actionLink\\|)([a-zA-Z0-9]*)\\|([a-zA-Z0-9_\\-]*)(\\})([^\\{]*)(\\{/actionLink\\})";
  final Pattern p = Pattern.compile(regexp, Pattern.MULTILINE | Pattern.DOTALL); // Compiles regular expression into Pattern.
  final Matcher m = p.matcher(wrapper.toString());
  final StringBuffer buf = new StringBuffer();
  // final String html = m.replaceAll(tutorialUrl + "/Hurzel");
  try {
    while (m.find() == true) {
      int i = 2;
      if (m.groupCount() != 6) {
        buf.append("{actionLink syntax error: " + m.groupCount() + ".}");
        continue;
      }
      // {actionLink|createUser|linda}create{/actionLink}
      m.appendReplacement(buf, "<a target=\"tutorial\" href=\"");
      buf.append(tutorialUrl);
      final String type = m.group(i++); // createUser
      if (type == null) {
        buf.append("\">create</a>");
        continue;
      }
      buf.append("?type=").append(type).append("&ref=");
      final String ref = m.group(i++);
      if (ref == null) {
        buf.append("\">create</a>");
        continue;
      }
      buf.append(ref).append("\"><img src=\"images/actionlink_add.png\" style=\"vertical-align:middle;border:none;\" />");
      i++; // }
      final String label = m.group(i++);
      if (label == null) {
        buf.append("\">create</a>");
        continue;
      }
      buf.append(label);
      buf.append("</a>");
    }
    m.appendTail(buf);
  } catch (final Exception ex) {
    log.error(ex.getMessage(), ex);
  }

  // html = html.replace("{actionLink}", tutorialUrl);
  // <link url="{actionLink}?type=createUser&amp;ref=linda" target="tutorial">create</link>
  caw.write(buf.toString());
  // caw.write(wrapper.toString().substring(0, wrapper.toString().indexOf("</body>") - 1));
  // caw.write("<p>\n<center>" + messages.getString("Visitor") + "<font color='red'>" + counter.getCounter() + "</font></center>");
  // caw.write("\n</body></html>");
  resp.setContentLength(caw.toString().length());
  out.write(caw.toString());
  out.close();
}
 
Example 19
Source File: FlashPrintElement.java    From jasperreports with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Resolves hyperlink placeholders to URLs in a Flash variable.
 * 
 * @param text the text in which hyperlink placeholders are to be replaced
 * @param element the print element where hyperlink parameters will be looked for
 * @param linkProducer the hyperlink producer which transforms hyperlink
 * objects to String URLs
 * @return the text with hyperlink placeholders replaced by URLs
 * @see #makeLinkPlaceholder(String)
 */
public static String resolveLinks(String text,
		JRGenericPrintElement element,
		JRHyperlinkProducer linkProducer,
		boolean prepareForSerialization)
{
	Matcher matcher = LINK_PATTERN.matcher(text);
	StringBuffer xml = new StringBuffer();
	List<HyperlinkData> hyperlinksData = new ArrayList<HyperlinkData>();

	while (matcher.find())
	{
		String paramName = matcher.group(LINK_PARAM_NAME_GROUP);
		JRPrintHyperlink hyperlink = 
			(JRPrintHyperlink) element.getParameterValue(paramName);
		
		String replacement;
		if (hyperlink == null)
		{
			if (log.isWarnEnabled())
			{
				log.warn("Hyperlink parameter " + paramName 
						+ " not found in element");
			}
			
			replacement = null;
		}
		else
		{
			replacement = linkProducer.getHyperlink(hyperlink);
			if (prepareForSerialization) {
				String id = String.valueOf(hyperlink.hashCode() & 0x7FFFFFFF);

				HyperlinkData hyperlinkData = new HyperlinkData();
				hyperlinkData.setId(id);
				hyperlinkData.setHref(replacement);
				hyperlinkData.setHyperlink(hyperlink);
				hyperlinkData.setSelector("._jrHyperLink." + hyperlink.getLinkType());
				replacement = "jrhl-" + id + ";" + hyperlink.getLinkType();

				hyperlinksData.add(hyperlinkData);
			}
		}
		
		if (replacement == null)
		{
			replacement = "";
		}
		else
		{
			try
			{
				if (!prepareForSerialization) {
					replacement = URLEncoder.encode(replacement, "UTF-8");
				}
			}
			catch (UnsupportedEncodingException e)
			{
				throw new JRRuntimeException(e);
			}
		}
		
		matcher.appendReplacement(xml, replacement);
	}
	matcher.appendTail(xml);

	if (hyperlinksData.size() > 0) {
		element.setParameterValue("hyperlinksData", hyperlinksData);
	}
	
	return xml.toString();

}
 
Example 20
Source File: CustomizableTraceInterceptor.java    From spring4-understanding with Apache License 2.0 3 votes vote down vote up
/**
 * Adds a comma-separated list of the short {@code Class} names of the
 * method argument types to the output. For example, if a method has signature
 * {@code put(java.lang.String, java.lang.Object)} then the value returned
 * will be {@code String, Object}.
 * @param methodInvocation the {@code MethodInvocation} being logged.
 * Arguments will be retrieved from the corresponding {@code Method}.
 * @param matcher the {@code Matcher} containing the state of the output
 * @param output the {@code StringBuffer} containing the output
 */
private void appendArgumentTypes(MethodInvocation methodInvocation, Matcher matcher, StringBuffer output) {
	Class<?>[] argumentTypes = methodInvocation.getMethod().getParameterTypes();
	String[] argumentTypeShortNames = new String[argumentTypes.length];
	for (int i = 0; i < argumentTypeShortNames.length; i++) {
		argumentTypeShortNames[i] = ClassUtils.getShortName(argumentTypes[i]);
	}
	matcher.appendReplacement(output,
			Matcher.quoteReplacement(StringUtils.arrayToCommaDelimitedString(argumentTypeShortNames)));
}