Matcher.appendReplacement与文字文本 [英] Matcher.appendReplacement with literal text

查看:218
本文介绍了Matcher.appendReplacement与文字文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Matcher.appendReplacement()它工作得很好,直到我的替换字符串中有$ 2:

I am using Matcher.appendReplacement() and it worked great until my replacement string had a $2 in it:


请注意,替换字符串
中的反斜杠(\)和
符号($)可能导致结果与处理时的结果不同
作为
字面替换字符串。 $
符号可以被视为对
捕获子序列的引用,如上面描述的
,反斜杠用于
替换字符串中的
转义文字字符。

Note that backslashes ( \ ) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string. Dollar signs may be treated as references to captured subsequences as described above, and backslashes are used to escape literal characters in the replacement string.

是否有一个方便的方法可以逃避所有反斜杠\和美元符号$反斜杠?或者我必须自己写一个?这听起来不是那么难,如果他们给你一个>,那就太好了:(

Is there a convenience method somewhere that will escape all backslashes \ and dollar signs $ with a backslash? Or do I have to write one myself? It sounds like it's not that hard, just would be nice if they gave you one >:(

编辑:,因为他们给你一个,我需要 replace(> :(,:-));

edit: since they do give you one, I need to replace(">:(", ":-)");

推荐答案

使用 Matcher.quoteReplacement

不幸的是,易用性在这种情况下与强类型冲突。[说明:Java静态类型的对象 java.lang.String char 的任何不可变序列。它不是告诉你原始数据的格式。在这种情况下,我们的文本可能对用户有意义,用迷你语言编码的文本用于替换,文本用迷你语言编码用于模式.Java类型系统没有办法区分这些(虽然您可以使用基于注释的类型检查器来做有趣的事情,通常是避免XSS或SQL /命令注入漏洞)。对于模式迷你语言,您可以使用 Pattern.compile 进行转换,尽管这是一种特定用途,大多数API方法都会忽略它(为了便于使用)。可以编写等效的 ReplacementText.compile 。此外,您可以忽略迷你语言并将库作为DSL。但这一切都无助于随意使用。]

Unfortunately "ease of use" in this case conflicts with strong typing. [Explanation: An object of Java static type java.lang.String is any immutable sequence of chars. It doesn't tell you the format of that raw data. In this scenario we have text probably meaningful to the user, text encoded in a mini-language for replacement and text encoded in a mini-language for the pattern. The Java type system has no way of distinguishing these (although you can do fun things with annotation-based type checkers, often to avoid XSS or SQL/command injection vulnerabilities). For the pattern mini-language you can to a form of conversion with Pattern.compile although that is a specific use and most APIs methods ignore it (for ease of use). An equivalent ReplacementText.compile could be written. Further, you could ignore the mini-languages and go for libraries as "DSLs". But all this doesn't help casual ease of use.]

这篇关于Matcher.appendReplacement与文字文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆