2014-12-06 61 views
0

我有看起来像下面的字符串,我想通过并删除不包含标记_JJ或_NN的行。删除整行,如果它不包含短语

输入:

Hello_NN 
and_CC 
Happy_JJ 
Birthday_NN 
to_TO 
me_NN 
!_! 

输出:

Hello_NN 
Happy_JJ 
Birthday_NN 
me_NN 
+0

尝试使用replaceAll方法用正则表达式,在这样的情况下工作吗? – TeaAnyOne 2014-12-06 16:53:33

+2

发布没有工作并解释任何问题的尝试代码 – Reimeus 2014-12-06 16:54:40

+1

问题不明确?他说他有一个字符串并发布了内容,他想知道如何将其转换为输出 – mukunda 2014-12-07 05:46:50

回答

2

方法1:

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

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

3)如果条件不满足,则跳过该行。

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


方法2:

小提琴在regex101.com直到你得到一个工作正则表达式:

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

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. 
相关问题