java 在java中删除特定单词之后或之前的部分字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29175008/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove part of string after or before a specific word in java
提问by user3286012
Is there a command in java to remove the rest of the string after or before a certain word;
java中是否有命令可以删除某个单词之后或之前的其余字符串;
Example:
例子:
Remove substring before the word "taken"
删除单词“taken”之前的子字符串
before: "I need this words removed taken please"
之前:“我需要删除这句话,请取走”
after:
后:
"taken please"
“请拿走”
回答by Crazyjavahacking
String are immutable, you can however find the word and create a substring:
字符串是不可变的,但是您可以找到单词并创建一个子字符串:
public static String removeTillWord(String input, String word) {
return input.substring(input.indexOf(word));
}
removeTillWord("I need this words removed taken please", "taken");
回答by Andremoniy
There is apache-commons-lang
class StringUtils
that contains exactly you want:
有apache-commons-lang
类StringUtils
包含正是你想要的:
e.g. public static String substringBefore(String str, String separator)
例如 public static String substringBefore(String str, String separator)
回答by Gibolt
Clean way to safely remove until a string
干净的方式安全地移除直到一个字符串
String input = "I need this words removed taken please";
String token = "taken";
String result = input.contains(token)
? token + StringUtils.substringAfter(string, token)
: input;
Apache StringUtilsfunctions are null-, empty-, and no match- safe
Apache StringUtils函数是空、空和无匹配安全的
回答by Eugene
Since OP provided clear requirements
由于 OP 提供了明确的要求
Remove the rest of the string afteror beforea certain word
在某个单词之后或之前删除字符串的其余部分
and nobody has fulfilled those yet, here is my approach to the problem. There are certain rules to the implementation, but overall it should satisfy OP's needs, if he or she comes to revisit the question.
还没有人实现这些,这是我解决问题的方法。实施有一定的规则,但总的来说,如果他或她重新审视这个问题,它应该满足 OP 的需求。
public static String remove(String input, String separator, boolean before) {
Objects.requireNonNull(input);
Objects.requireNonNull(separator);
if (input.trim().equals(separator)) {
return separator;
}
if (separator.isEmpty() || input.trim().isEmpty()) {
return input;
}
String[] tokens = input.split(separator);
String target;
if (before) {
target = tokens[0];
} else {
target = tokens[1];
}
return input.replace(target, "");
}
回答by Eugene
public static String foo(String str, String remove) {
return str.substring(str.indexOf(remove));
}