我想替换以下字符串的第一次出现。
String test = "see Comments, this is for some test, help us"
**如果测试包含输入如下不应该取代
- 看评论,(与空间末)
- 看评论,
- 看评论**
我想要得到的输出如下,
Output: this is for some test, help us
提前致谢,
我想替换以下字符串的第一次出现。
String test = "see Comments, this is for some test, help us"
**如果测试包含输入如下不应该取代
我想要得到的输出如下,
Output: this is for some test, help us
提前致谢,
您可以使用replaceFirst(String regex, String replacement)
字符串的方法。
你应该有利于编写自己的代码的使用已经测试并有据可查的库。
org.apache.commons.lang3.
StringUtils.replaceOnce("coast-to-coast", "coast", "") = "-to-coast"
甚至还有一个版本是不区分大小写(这是很好)。
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.7</version>
</dependency>
我的回答是的增强: https://stackoverflow.com/a/10861856/714112
使用substring(int beginIndex)
String test = "see Comments, this is for some test, help us";
String newString = test.substring(test.indexOf(",") + 2);
System.out.println(newString);
OUTPUT:
这对于一些测试,帮助我们
您可以使用下面的语句来替换字符串的第一次出现。
String result = input.replaceFirst(Pattern.quote(stringToReplace), stringToReplaceWith);
此链接有包括测试用例完整的程序。
您可以使用下面的方法。
public static String replaceFirstOccurrenceOfString(String inputString, String stringToReplace,
String stringToReplaceWith) {
int length = stringToReplace.length();
int inputLength = inputString.length();
int startingIndexofTheStringToReplace = inputString.indexOf(stringToReplace);
String finalString = inputString.substring(0, startingIndexofTheStringToReplace) + stringToReplaceWith
+ inputString.substring(startingIndexofTheStringToReplace + length, inputLength);
return finalString;
}
下面的链接替换使用和不使用正则表达式使用字符串的第一次出现提供了范例。
使用字符串replaceFirst的分隔符的第一个实例交换到一些独特的东西:
String input = "this=that=theother"
String[] arr = input.replaceFirst("=", "==").split('==',-1);
String key = arr[0];
String value = arr[1];
System.out.println(key + " = " + value);