简体   繁体   English

替换为忽略大小写

[英]Replace with ignore case sensitive

I need to replace $achieved$ from a string and it should be case insensitive. 我需要从字符串中替换$achieved$ ,并且它应不区分大小写。 Because sometimes in string from server we get $ACHIeved$ , hence it should ignore case sensitive. 因为有时从服务器以字符串形式获取$ACHIeved$ ,所以它应该忽略大小写。 I am using below code. 我正在使用下面的代码。

stringWithoutFormating.replace(Constant.PROGRAM_DETAILS_ENTRY_CONTENT_FIELDS.achieved, String.valueOf(achieved));

I have tried with (?i) as well but its not working. 我也尝试过(?i) ,但无法正常工作。
Can it be done with regex, if yes what should be the regex? 可以用正则表达式完成吗,如果是,则正则表达式应该是什么?

First of all, replace performs literal string replacement, and does not accept a regex as its first argument. 首先, replace执行文字字符串替换,并且不接受正则表达式作为其第一个参数。 You need to use replaceFirst or replaceAll . 您需要使用replaceFirstreplaceAll Next, $ is a special regex char (it matches end of string), so it must be escaped. 接下来, $是一个特殊的正则表达式char(它匹配字符串的结尾),因此必须将其转义。 You may use Pattern.quote for that. 您可以为此使用Pattern.quote So, you may use 因此,您可以使用

stringWithoutFormating = stringWithoutFormating.replaceAll("(?i)" + Pattern.quote(Constant.PROGRAM_DETAILS_ENTRY_CONTENT_FIELDS.achieved), String.valueOf(achieved).replace("$", "\\$"));

Here, (?i) will make the search case insensitive, Pattern.quote(Constant.PROGRAM_DETAILS_ENTRY_CONTENT_FIELDS.achieved) will turn $achieved$ into \\$achieved\\$ , and then the replacement will take place. 在这里, (?i)将使搜索不区分大小写, Pattern.quote(Constant.PROGRAM_DETAILS_ENTRY_CONTENT_FIELDS.achieved)会将$achieved$变成\\$achieved\\$ ,然后替换将发生。 The .replace("$", "\\\\$") performed on the replacement is necessary to escape literal $ in the replacement. 替换执行的.replace("$", "\\\\$")是必需的,以便在替换中转义文字$

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

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