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

The following examples show how to use java.util.regex.Matcher#quoteReplacement() . 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: NewCommandMacro.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public String executeMacro(TeXParser tp, String[] args) {
    String code = macrocode.get(args[0]);
    String rep;
    int nbargs = args.length - 11;
    int dec = 0;


    if (args[nbargs + 1] != null) {
        dec = 1;
        rep = Matcher.quoteReplacement(args[nbargs + 1]);
        code = code.replaceAll("#1", rep);
    } else if (macroreplacement.get(args[0]) != null) {
        dec = 1;
        rep = Matcher.quoteReplacement(macroreplacement.get(args[0]));
        code = code.replaceAll("#1", rep);
    }

    for (int i = 1; i <= nbargs; i++) {
        rep = Matcher.quoteReplacement(args[i]);
        code = code.replaceAll("#" + (i + dec), rep);
    }

    return code;
}
 
Example 2
Source File: JRT.java    From vscrawler with Apache License 2.0 6 votes vote down vote up
public static Integer replaceAll(Object orig_value_obj, Object repl_obj, Object ere_obj, StringBuffer sb, String convfmt) {
	String orig_value = toAwkString(orig_value_obj, convfmt);
	String repl = toAwkString(repl_obj, convfmt);
	String ere = toAwkString(ere_obj, convfmt);
	// remove special meaning for backslash and dollar signs
	repl = Matcher.quoteReplacement(repl);
	sb.setLength(0);

	Pattern p = Pattern.compile(ere);
	Matcher m = p.matcher(orig_value);
	int cnt = 0;
	while (m.find()) {
		++cnt;
		m.appendReplacement(sb, repl);
	}
	m.appendTail(sb);
	return Integer.valueOf(cnt);
}
 
Example 3
Source File: UriComponents.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
static String expandUriComponent(String source, UriTemplateVariables uriVariables) {
	if (source == null) {
		return null;
	}
	if (source.indexOf('{') == -1) {
		return source;
	}
	if (source.indexOf(':') != -1) {
		source = sanitizeSource(source);
	}
	Matcher matcher = NAMES_PATTERN.matcher(source);
	StringBuffer sb = new StringBuffer();
	while (matcher.find()) {
		String match = matcher.group(1);
		String variableName = getVariableName(match);
		Object variableValue = uriVariables.getValue(variableName);
		if (UriTemplateVariables.SKIP_VALUE.equals(variableValue)) {
			continue;
		}
		String variableValueString = getVariableValueAsString(variableValue);
		String replacement = Matcher.quoteReplacement(variableValueString);
		matcher.appendReplacement(sb, replacement);
	}
	matcher.appendTail(sb);
	return sb.toString();
}
 
Example 4
Source File: Stash.java    From crate with Apache License 2.0 6 votes vote down vote up
/**
 * Lookup a value from the stash adding support for a special key ({@code $_path}) which
 * returns a string that is the location in the path of the of the object currently being
 * unstashed. This is useful during documentation testing.
 */
private Object getValue(List<Object> path, String key) throws IOException {
    Matcher matcher = PATH.matcher(key);
    if (false == matcher.find()) {
        return getValue(key);
    }
    StringBuilder pathBuilder = new StringBuilder();
    Iterator<Object> element = path.iterator();
    if (element.hasNext()) {
        pathBuilder.append(element.next().toString().replace(".", "\\."));
        while (element.hasNext()) {
            pathBuilder.append('.');
            pathBuilder.append(element.next().toString().replace(".", "\\."));
        }
    }
    String builtPath = Matcher.quoteReplacement(pathBuilder.toString());
    StringBuffer newKey = new StringBuffer(key.length());
    do {
        matcher.appendReplacement(newKey, builtPath);
    } while (matcher.find());
    matcher.appendTail(newKey);
    return getValue(newKey.toString());
}
 
Example 5
Source File: DebugStacktraceRenderer.java    From datakernel with Apache License 2.0 6 votes vote down vote up
public static HttpResponse render(Throwable e, int code) {
	StringWriter writer = new StringWriter();
	e.printStackTrace(new PrintWriter(writer));
	Matcher matcher = STACK_TRACE_ELEMENT.matcher(writer.toString());
	StringBuffer stacktrace = new StringBuffer();
	while (matcher.find()) {
		String cls = matcher.group(2);
		String quotedFile = Matcher.quoteReplacement(cls.substring(0, cls.length() - 1).replace('.', '/').replaceAll("\\$.*(?:\\.|$)", ""));
		matcher.appendReplacement(stacktrace, "$1<a data-target=\"api/file/" + quotedFile + "$4$5\">$3</a>)");
	}
	matcher.appendTail(stacktrace);
	return HttpResponse.ofCode(500)
			.withHtml(DEBUG_SERVER_ERROR_HTML
					.replace("{title}", HttpUtils.getHttpErrorTitle(code))
					.replace("{stacktrace}", stacktrace));
}
 
Example 6
Source File: FetchCase.java    From HongsCORE with MIT License 6 votes vote down vote up
/**
 * fixSQLAlias 的内部方法
 * @param s
 * @param an
 * @return
 */
private static CharSequence fixSQLAliaz(CharSequence s, String an)
{
    Matcher m = SQL_ALIAS.matcher(s);
    String  n ;

    if (m.find()) {
            n = m.group(1);
        if ( ":".equals(n) || "!".equals(n)) {
            return s;
        }
            n = m.group(2);
        if (n == null) {
            n = m.group(3);
        }
        if (m.group(1) == null) {
            n = "`"+n+"` AS `"+an+"."+n+"`";
        } else {
            n = /* Alias */"`"+an+"."+n+"`";
        }
        n = Matcher.quoteReplacement(n);
        s = m.replaceFirst("$1"+n+"$4");
    }

    return s;
}
 
Example 7
Source File: UriMutator.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
private String getQueryValueForQueryParameters(String queryName,
		String queryParameters) {
	String queryValue = null;
	String[] queries = queryParameters.split("&");
	String queryRegEx = "^" + Matcher.quoteReplacement(queryName) + "=.+";

	for (String query : queries) {
		if (query.matches(queryRegEx)) {
			int indexOfQueryValue = queryRegEx.length() - 3;
			queryValue = query.substring(indexOfQueryValue);
			break;
		}
	}

	return queryValue;
}
 
Example 8
Source File: JPackerParser.java    From jpexs-decompiler with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Executes the parser in order to parse the script with the expressions
 * added via {@link #remove(String)}, {@link #ignore(String)},
 * {@link #replace(String,String)} and {@link #replace(String,Evaluator)}.
 * Using a {@link ReplacementStrategy} object, a custom replacement
 * algorithm can be used.
 *
 * @param input
 *            The script to be parsed
 * @param strategy
 *            The {@link ReplacementStrategy} object for custom replacement
 * @return The parsed script
 */
public String exec(String input, ReplacementStrategy strategy) {
    Matcher matcher = buildPatterns().matcher(input);
    StringBuffer sb = new StringBuffer(input.length());
    while (matcher.find()) {
        String rep = strategy.replace(jpatterns, matcher);
        if (rep != null && !rep.isEmpty()) {
            rep = Matcher.quoteReplacement(rep);
        }
        matcher.appendReplacement(sb, rep);
    }
    matcher.appendTail(sb);
    return DELETED.matcher(sb).replaceAll("");
}
 
Example 9
Source File: ReplaceText.java    From nifi with Apache License 2.0 5 votes vote down vote up
/**
 * If we have a '$' followed by anything other than a number, then escape
 * it. E.g., '$d' becomes '\$d' so that it can be used as a literal in a
 * regex.
 */
private static String normalizeReplacementString(String replacement) {
    String replacementFinal = replacement;
    if (REPLACEMENT_NORMALIZATION_PATTERN.matcher(replacement).find()) {
        replacementFinal = Matcher.quoteReplacement(replacement);
    }
    return replacementFinal;
}
 
Example 10
Source File: Template.java    From spring-boot-cookbook with Apache License 2.0 5 votes vote down vote up
/**
 * 简单实现${}模板功能
 * 如${var1} content ${var2} 其中 ${var1}, ${var2} 为占位符. 可用相关变量进行替换
 *
 * @param template 模板字符串
 * @param params   需要被替换的变量名和变量值之间的映射关系
 * @return
 */
public static String process(String template, Map<String, String> params) {
    Assert.notNull(template, "template must not be null");
    Assert.notEmpty(params, "params must not be empty");
    for (Map.Entry<String, String> entry : params.entrySet()) {
        String replacement = entry.getValue();
        replacement = Matcher.quoteReplacement(replacement);
        template = template.replaceAll("\\$\\{".concat(entry.getKey().trim()).concat("\\}"), replacement);
    }
    return template;
}
 
Example 11
Source File: FilterProvider.java    From apk-dependency-graph with Apache License 2.0 5 votes vote down vote up
public Filter<String> makePathFilter() {
    String replacement = Matcher.quoteReplacement(File.separator);
 replacement = Matcher.quoteReplacement(replacement);
    String packageNameAsPath = inputFilters.getPackageName().replaceAll("\\.", replacement);
    String packageNameRegex = ".*" + packageNameAsPath + ".*";
    RegexFilter filter = new RegexFilter(packageNameRegex);
    
    return filter;
}
 
Example 12
Source File: JRT.java    From vscrawler with Apache License 2.0 5 votes vote down vote up
public static Integer replaceFirst(Object orig_value_obj, Object repl_obj, Object ere_obj, StringBuffer sb, String convfmt) {
	String orig_value = toAwkString(orig_value_obj, convfmt);
	String repl = toAwkString(repl_obj, convfmt);
	String ere = toAwkString(ere_obj, convfmt);
	// remove special meaning for backslash and dollar signs
	repl = Matcher.quoteReplacement(repl);
	sb.setLength(0);
	sb.append(orig_value.replaceFirst(ere, repl));
	if (sb.toString().equals(orig_value)) {
		return ZERO;
	} else {
		return ONE;
	}
}
 
Example 13
Source File: BtcFormat.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Return a representation of the pattern used by this instance for formatting and
 * parsing.  The format is similar to, but not the same as the format recognized by the
 * {@link Builder#pattern} and {@link Builder#localizedPattern} methods.  The pattern
 * returned by this method is localized, any currency signs expressed are literally, and
 * optional fractional decimal places are shown grouped in parentheses.
 */
public String pattern() {
    synchronized (numberFormat) {
        StringBuilder groups = new StringBuilder();
        for (int group : decimalGroups) {
            groups.append("(").append(Strings.repeat("#", group)).append(")");
        }
        DecimalFormatSymbols s = numberFormat.getDecimalFormatSymbols();
        String digit = String.valueOf(s.getDigit());
        String exp = s.getExponentSeparator();
        String groupSep = String.valueOf(s.getGroupingSeparator());
        String moneySep = String.valueOf(s.getMonetaryDecimalSeparator());
        String zero = String.valueOf(s.getZeroDigit());
        String boundary = String.valueOf(s.getPatternSeparator());
        String minus = String.valueOf(s.getMinusSign());
        String decSep = String.valueOf(s.getDecimalSeparator());

        String prefixAndNumber = "(^|" + boundary + ")" +
                "([^" + Matcher.quoteReplacement(digit + zero + groupSep + decSep + moneySep) + "']*('[^']*')?)*" +
                "[" + Matcher.quoteReplacement(digit + zero + groupSep + decSep + moneySep + exp) + "]+";

        return numberFormat.toLocalizedPattern().
                replaceAll(prefixAndNumber, "$0" + groups.toString()).
                replaceAll("¤¤", Matcher.quoteReplacement(coinCode())).
                replaceAll("¤", Matcher.quoteReplacement(coinSymbol()));
    }
}
 
Example 14
Source File: ClassInfo.java    From L2jOrg with GNU General Public License v3.0 4 votes vote down vote up
/**
 * @return the escaped class client Id formatted to be displayed on a HTML.
 */
public String getEscapedClientCode() {
    return Matcher.quoteReplacement(getClientCode());
}
 
Example 15
Source File: StringUtilities.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Parse special characters with String replacement
 */
public static String replaceSpecials(String replacement) {

	return Matcher.quoteReplacement(replacement);
}
 
Example 16
Source File: Default.java    From HongsCORE with MIT License 4 votes vote down vote up
public Object merge(Value watch, String param) throws Wrong {
    Map vars = watch.getCleans();
    Set a = Synt.setOf(); // 缺失的键
    int i = 0; // 缺值数量
    int j = 0; // 取值数量

    /**
     * 以下代码源自 Syno.inject
     */

    Matcher matcher = INJ.matcher(param);
    StringBuffer sb = new StringBuffer();
    Object       ob;
    String       st;
    String       sd;

    while  ( matcher.find() ) {
        st = matcher.group(1);

        if (! st.equals("$")) {
            if (st.startsWith("{")) {
                st = st.substring(1, st.length() - 1);
                // 默认值
                int p  = st.indexOf  ("|");
                if (p != -1) {
                    sd = st.substring(1+p);
                    st = st.substring(0,p);
                } else {
                    sd = "";
                }
            } else {
                    sd = "";
            }

            // 记下缺失的字段
            if (! vars.containsKey(st)) {
                a.add( st );
                i ++;
            }   j ++;

                ob  = vars.get (st);
            if (ob != null) {
                st  = ob.toString();
            } else {
                st  = sd;
            }
        }

        st = Matcher.quoteReplacement(st);
        matcher.appendReplacement(sb, st);
    }

    /**
     * 创建时不理会缺失的值, 作空处理即可
     * 更新时除非全部未给值, 否则校验错误
     */
    if (watch.isUpdate( )) {
        if (i != j) {
            throw new Wrong("core.error.default.need.vars", a.toString());
        } else {
            return  BLANK ;
        }
    }

    matcher.appendTail(sb);
    return sb.toString(  );
}
 
Example 17
Source File: TokenSub.java    From incubator-heron with Apache License 2.0 4 votes vote down vote up
/**
 * Given a static config map, substitute occurrences of ${HERON_*} variables
 * in the provided path string
 *
 * @param config a static map config object of key value pairs
 * @param pathString string representing a path including ${HERON_*} variables
 * @return String string that represents the modified path
 */
public static String substitute(Config config, String pathString) {

  // trim the leading and trailing spaces
  String trimmedPath = pathString.trim();

  if (isURL(trimmedPath)) {
    return substituteURL(config, trimmedPath);
  }

  // get platform independent file separator
  String fileSeparator = Matcher.quoteReplacement(File.separator);

  // split the trimmed path into a list of components
  List<String> fixedList = Arrays.asList(trimmedPath.split(fileSeparator));
  List<String> list = new LinkedList<>(fixedList);

  // substitute various variables
  for (int i = 0; i < list.size(); i++) {
    String elem = list.get(i);

    if ("${HOME}".equals(elem) || "~".equals(elem)) {
      list.set(i, System.getProperty("user.home"));

    } else if ("${JAVA_HOME}".equals(elem)) {
      String javaPath = System.getenv("JAVA_HOME");
      if (javaPath != null) {
        list.set(i, javaPath);
      }
    } else if (isToken(elem)) {
      Matcher m = TOKEN_PATTERN.matcher(elem);
      if (m.matches()) {
        String token = m.group(1);
        try {
          // For backwards compatibility the ${TOPOLOGY} token will match Key.TOPOLOGY_NAME
          if ("TOPOLOGY".equals(token)) {
            token = "TOPOLOGY_NAME";
          }
          Key key = Key.valueOf(token);
          String value = config.getStringValue(key);
          if (value == null) {
            throw new IllegalArgumentException(String.format("Config value %s contains "
                    + "substitution token %s but the corresponding config setting %s not found",
                pathString, elem, key.value()));
          }
          list.set(i, value);
        } catch (IllegalArgumentException e) {
          LOG.fine(String.format("Config value %s contains substitution token %s which is "
                  + "not defined in the Key enum, which is required for token substitution",
              pathString, elem));
        }
      }
    }
  }

  return combinePaths(list);
}
 
Example 18
Source File: SyslogLayout.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
protected SyslogLayout(final Facility facility, final boolean includeNL, final String escapeNL, final Charset charset) {
    super(charset);
    this.facility = facility;
    this.includeNewLine = includeNL;
    this.escapeNewLine = escapeNL == null ? null : Matcher.quoteReplacement(escapeNL);
}
 
Example 19
Source File: TString.java    From Voovan with Apache License 2.0 3 votes vote down vote up
/**
 * 快速字符串替换算法
 *
 * @param source      源字符串
 * @param regex       正则字符串
 * @param replacement 替换字符串
 * @param flags  	  正则匹配标记 CASE_INSENSITIVE, MULTILINE, DOTALL, UNICODE_CASE, CANON_EQ, UNIX_LINES, LITERAL, UNICODE_CHARACTER_CLASS, COMMENTS
 * @param quoteReplacement 对 replacement 是否进行转移
 * @return 替换后的字符串
 */
public static String fastReplaceAll(String source, String regex, String replacement, Integer flags, boolean quoteReplacement) {
	Pattern pattern = getCachedPattern(regex, flags);
	if(quoteReplacement) {
		replacement = Matcher.quoteReplacement(replacement);
	}
	return pattern.matcher(source).replaceAll(replacement);
}
 
Example 20
Source File: EscapeChars.java    From pra with MIT License 2 votes vote down vote up
/**
* Escape <tt>'$'</tt> and <tt>'\'</tt> characters in replacement strings.
* 
* <P>Synonym for <tt>Matcher.quoteReplacement(String)</tt>.
* 
* <P>The following methods use replacement strings which treat 
* <tt>'$'</tt> and <tt>'\'</tt> as special characters:
* <ul>
* <li><tt>String.replaceAll(String, String)</tt>
* <li><tt>String.replaceFirst(String, String)</tt>
* <li><tt>Matcher.appendReplacement(StringBuffer, String)</tt>
* </ul>
* 
* <P>If replacement text can contain arbitrary characters, then you 
* will usually need to escape that text, to ensure special characters 
* are interpreted literally.
*/
public static String forReplacementString(String aInput){
  return Matcher.quoteReplacement(aInput);
}