简体   繁体   English

有没有办法使用正则表达式包含变量来替换字符串中的字符

[英]Is There A Way To Use Regex Containing Variables To Replace Characters In A String

I already have the code s.replaceFirst("\\\\.", ""); 我已经有了代码s.replaceFirst("\\\\.", ""); . This replaces the dot in the given string s. 这将替换给定字符串s中的点。 But my problem is, that it shall be able to change, what is going to be replaced. 但是我的问题是,它应该能够更改,将要替换的内容。 Like for example, the programm has to replace now a question mark. 例如,该程序现在必须替换问号。 I tried to do it as following: 我尝试这样做,如下所示:

String characterToReplace = "?";
s = s.replaceFirst("\\" + characterToReplace, "");

But that just creates errors. 但这只会产生错误。

Try using Pattern.quote , discussed here : 尝试使用Pattern.quote ,在这里讨论:

import java.util.regex.Pattern;

// ...

String characterToReplace = "?";
s = s.replaceFirst(Pattern.quote(characterToReplace), "");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM