2014-04-25 181 views
1

我有一個字符串:字符串分割,並得到perticular串

"cards_NNS may_MD be_VB worth_JJ hundreds_NNS a_DT report_NN" 

現在,我試圖讓從具有_NNS and _NN and _JJ在單詞的末尾給定的字符串的字符串數組的那些話。

輸出:

cards worth hundreds report 

我曾嘗試:

string.split("[^_NNS]+"); 

人請給我一些想法。

+0

thanx您寶貴的評論,但我已經tryied這個它不工作,根據我的需求 – learner

+0

正則表達式'(\\ w +(?=(_JJ)|(_NNS)|(_NN)))'將匹配你想要的 – Baby

回答

0

代碼

String val = "cards_NNS may_MD be_VB worth_JJ hundreds_NNS a_DT report_NN"; 
String[] allVal = val.split(" "); 
for(String each: allVal){ 
    if(each.endsWith("_NNS") || each.endsWith("_NN") || each.endsWith("_JJ")){ 
     System.out.println(each); 
    } 
} 

輸出:

cards_NNS 
worth_JJ 
hundreds_NNS 
report_NN 

編輯

代碼

String val = "cards_NNS may_MD be_VB worth_JJ hundreds_NNS a_DT report_NN"; 
String[] allVal = val.split(" "); 
for(String each: allVal){ 
    if(each.endsWith("_NNS")){ 
     System.out.println(each.substring(0, each.length() - 4)); 
    }else if(each.endsWith("_NN") || each.endsWith("_JJ")){ 
     System.out.println(each.substring(0, each.length() - 3)); 
    } 
} 

輸出

cards 
worth 
hundreds 
report 
+0

剪下* _ext *部分。 –

+0

Thanx Gaurav!我們可以從輸出詞中刪除_NNS _NN _JJ意思是隻需要價值數百的報告。 – learner

+0

如果你解釋'ext parts'是什麼,那將會很好。 – guptakvgaurav

0

,如果你想這樣做在一個分割操作這已成爲一個相當複雜的正則表達式。這是一個雖然工作方法:

String input = "cards_NNS may_MD be_VB worth_JJ hundreds_NNS a_DT report_NN"; 
String[] output = input.split("_(JJ|NNS?).*?(?=\\b(\\w*_(JJ|NNS?)|$))"); 
System.out.println(Arrays.toString(output)); 

這將打印

[cards, worth, hundreds, report] 

正則表達式找到一個後綴爲_JJ_NN_NNS開始。然後繼續,直到它找到以一個所提到的後綴結尾的單詞或字符串的結尾($)。

1

您可以使用PatternMatcher這裏:

String str = "cards_NNS may_MD be_VB worth_JJ hundreds_NNS a_DT report_NN"; 

Matcher matcher = Pattern.compile("(\\w+?)_(?:NNS|JJ|NN)\\b").matcher(str); 

while (matcher.find()) { 
    System.out.println(matcher.group(1)); 
} 

這將找到的話所有這些序列,與_NNS_JJ_NN結束。然後第一個捕獲組在_之前捕獲該字符串。

+0

@aashish_soni不客氣:) –

+0

@RohitJain你在這裏使用正則表達式嗎? –

0

嘗試了這一點:

String str = "cards_NNS may_MD be_VB worth_JJ hundreds_NNS a_DT report_NN"; 
    Pattern pattern = Pattern.compile("([^\\s]+?)_(NNS|NN|JJ)\\b"); 
    Matcher matcher = pattern.matcher(str); 

    while (matcher.find()) { 
     System.out.println(matcher.group(1)); 
    } 

輸出:


價值
數百
報告