如果不包含短语,请删除整行

时间:2014-12-06 16:50:44

标签: java string

我的字符串如下所示,我想通过并删除不包含标签_JJ或_NN的行。

输入:

Hello_NN
and_CC
Happy_JJ
Birthday_NN
to_TO
me_NN
!_!

输出:

Hello_NN
Happy_JJ
Birthday_NN
me_NN

2 个答案:

答案 0 :(得分:2)

方法1:

1)创建一个处理每一行的循环。

2)在循环中,使用String.contains()函数查看该行是否包含“_JJ”或“_NN”

3)如果条件失败,请跳过该行。

4)如果条件通过,则输出该行。


方法2:

在regex101.com上小提琴,直到你得到正则表达式:

foo = bar.replaceAll( "(?m)^.+(?<!JJ|NN)(\n|$)", "" );

答案 1 :(得分:1)

一种解决方案是将您想要的行添加到新字符串中,而不是从已有的字符串中删除:

String newOutput = "";
while(! endOfInput){ // While you have stuff to read
   String temp = input.readLine(); // Get line
   if(temp.contains("_JJ") || temp.contains("_NN"){ // If the line contains something we want to keep
      newOutput += temp + "\n"; // Add it to new output, with new line marker
   }
}
// Display new output here.
相关问题