简体   繁体   English

在java中的特定单词之后或之前删除部分字符串

[英]Remove part of string after or before a specific word in java

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" 在“take”之前删除子字符串

before: "I need this words removed taken please" 之前:“我需要删除这个词取悦”

after: 后:

"taken please" “请取悦”

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");

There is apache-commons-lang class StringUtils that contains exactly you want: 有一个apache-commons-langStringUtils ,它包含你想要的:

eg public static String substringBefore(String str, String separator) 例如public static String substringBefore(String str, String separator)

public static String foo(String str, String remove) {
     return str.substring(str.indexOf(remove));
}

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 StringUtils functions are null-, empty-, and no match- safe Apache StringUtils函数为null-,empty-,并且不匹配安全

Since OP provided clear requirements 由于OP提供了明确的要求

Remove the rest of the string after or before a 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, "");
}

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

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