下面列出了java.util.regex.Matcher#quoteReplacement ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 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());
}
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));
}
/**
* 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;
}
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;
}
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();
}
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);
}
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;
}
/**
* 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("");
}
/**
* 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()));
}
}
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;
}
}
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;
}
/**
* 简单实现${}模板功能
* 如${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;
}
/**
* 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;
}
/**
* 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);
}
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( );
}
/**
* @return the escaped class client Id formatted to be displayed on a HTML.
*/
public String getEscapedClientCode() {
return Matcher.quoteReplacement(getClientCode());
}
/**
* Parse special characters with String replacement
*/
public static String replaceSpecials(String replacement) {
return Matcher.quoteReplacement(replacement);
}
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);
}
/**
* 快速字符串替换算法
*
* @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);
}
/**
* 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);
}