删除android中特殊字符前的所有字符

时间:2015-09-18 08:46:24

标签: java regex string

我必须从字符##中移除$$之前的##$$abxcyhshbhs##xcznbx##。我正在使用:

string.split("\\#");

问题是它还会在#之后移除$$

6 个答案:

答案 0 :(得分:2)

改为使用replace()。

String text = "##$$abxcyhshbhs##xcznbx##";
text = text.replace("##$$", "$$");

答案 1 :(得分:0)

您可以使用下面的子字符串方法

string.substring(2);

答案 2 :(得分:0)

要从字面上删除前两个字符,请使用以下内容:

String s = "##$$abxcyhshbhs##xcznbx##";
s.substring(2, s.length());

这不会进行任何模式匹配以查找$$

答案 3 :(得分:0)

如果你真的想使用String.split(),你可以通过限制结果数量来做你想要的事情:

String str = "##$$abxcyhshbhs##xcznbx##";
str = str.split("##", 2)[1];

我不知道你的确切问题,但正如已经说过的那样,replace()或substring()可能是更好的选择。

答案 4 :(得分:0)

如果您在#之前有$$符号数量未知且它们不仅出现在字符串的开头,则可以使用以下replaceAll带正则表达式:

String re = "#+\\${2}"; 
String str = "##$$abxcyh###$$shbhs##xcznbx##"; 
System.out.println(str.replaceAll(re, "\\$\\$")); // Note escaped $ !!!
// => $$abxcyh$$shbhs##xcznbx##
// or
re = "#+(\\${2})";  // using capturing and back-references
System.out.println(str.replaceAll(re, "$1"));

请参阅IDEONE demo

在代码中使用时,不要忘记为变量赋值:

str = str.replaceAll("#+(\\${2})", "$1")

答案 5 :(得分:0)

如果您的目的是从字符串中第一次出现的##中移除##$$,那么以下代码段将会有所帮助:

if(yourString.startsWith("##$$")){
     yourString.replaceFirst("##$$","$$");
}

或者考虑到你的字符串中只有一个$$,以下内容会有所帮助:

String requiredString="";
String[] splitArr = yourString.split("\\$");
if ( splitArr.length > 1 ) {
    requiredString = "$$" + splitArr[splitArr.length-1];
}

我编写了一段代码here。您可以自行更改并执行。