如何在String(Java)中剪切关键字?

时间:2014-01-09 08:46:25

标签: java regex string

我在Java中有以下字符串:

String test = "Goof 23N, 45, 88, GOOF 33*, 12-24";

现在我想从字符串中删除“Goof”这个词,我想将原来的23N输入保存在一个单独的字符串中(但是如何删除这个关键字并保存原来输入的“23N”或“33 *” “)

for(String tmpTest : test.split(",")){

  if (tmpTest.toLowerCase.contains("goof")){
      String separateString = // implementation unclear
  }

}

7 个答案:

答案 0 :(得分:2)

可能你可以尝试一下:

    String test = "Goof 23N, 45, 88, GOOF 33*, 12-24";
    String value = test.replaceFirst("Goof", "");
  

输出:23N,45,88,GOOF 33 *,12-24

或者,如果你需要删除所有版本的'Goof'而没有大小写匹配,那么请检查:

    String test = "Goof 23N, 45, 88, GOOF 33*, 12-24";
    // (?i) in the below regex will ignore case while matching
    String value = test.replaceAll("(?i)Goof\\s*", "");
  

输出:23N,45,88,33 *,12-24

答案 1 :(得分:0)

这样的事可能会对你有所帮助。将您的if声明替换为下面的声明。

int index = tmpTest.toLowerCase().indexOf("goof");
if (index >= 0) {
  String value = tmpTest.substring(index + 5);
}

另外,请注意代码中的编译错误。

答案 2 :(得分:0)

您可以使用函数replaceAll(String regex, String replacement)

String test = "Goof 23N, 45, 88, GOOF 33*, 12-24";
test = test.replaceAll("Goof","").replaceAll("GOOF","");

答案 3 :(得分:0)

您希望replaceAll使用正则表达式 忽略大小写 。您可以将Pattern.quote()用于此目的:

String keyword = "gOOf";

String test = "Goof 23N, 45, 88, GOOF 33*, 12-24";
String replaceString = "(?i)" + Pattern.quote(keyword);

test = test.replaceAll(replaceString, "");
System.out.println(test);

输出

  

23N,45,88,33 *,12-24

在这里,如何编写“gOOf”并不重要,它将使用正则表达式替换所有出现的事件。

答案 4 :(得分:0)

还有一种方法可以做到......

        String text = "Goof     23N, 45, 88, GoOF 33*, 12-24";
        //if you want to remove trailing spaces use 'goof\\s*' as regex
        String regex="goof";
        Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);  
        Matcher m = p.matcher(text);        
        System.out.println(m.replaceAll(""));

答案 5 :(得分:0)

final String GOOF = "goof";
String input = "Goof 23N, 45, 88, GOOF 33*, 12-24";
String inputLawerCase = input.toLowerCase();
String inputWithoutGoof = inputLawerCase.replaceFirst(GOOF, "");
String output = input.substring(input.length() - inputWithoutGoof.length());

//In case Goof is not at the beginning of the string
int goofIndex = inputLawerCase.indexOf(GOOF);
output = input.substring(0, goofIndex) + input.substring(goofIndex + GOOF.length());

答案 6 :(得分:-1)

我认为有点伪代码的时间。

第1步

您想将String拆分为tokens。您可以使用String.split()

执行此操作
Let input equal "this, is, just, a, GOOFtest".
// It's a comma that separates each token, so let's split on that.
Let tokens equal input.split(",").

注意: 如果您想将输入保留为String,请不要执行此步骤。

第2步

解析您的数据,删除"GOOF"。您可以使用String.replaceAll()

for every token in tokens
    let token equal token.replaceAll("GOOF", nothing).

注意 :如果GOOF可能出现在不同的情况下,那么某些regexp就是时候了。这被称为metalanguage,它旨在分析​​和操纵String。您想要做的是,不考虑case,您可以使用?i运算符实现此目的。

String regex = "(?i)GOOF";
String parsedInput = input.replaceAll(regex, "");
// And that's the only bit of Java you're getting!!

第3步

????

第4步

利润!你有一个只包含值的数组,没有出现GOOF