2013-12-17 144 views
-9

我想打印含有模式_fact」這個詞。例如在下面的字符串要打印agg_day_adv_campaign_demand_factJava的正則表達式打印字

String text = 
    "FROM dt_dim AS d, "+ 
    "adj_dim AS adj " + 
    "cam_dim AS cam, " + 
    "agg_day_adv_campaign_demand_fact AS fact "; 
+2

你忘了,錯誤地張貼你的企圖:) – Maroun

+10

我相信你已經按**問**按鈕,而不是**請求代碼**按鈕 – Baby

+0

爲了得到建設性的答案,你總是要顯示我們試圖自己解決您的問題以及預期和收到的輸出/錯誤消息。 –

回答

0
String text = 
       "FROM dt_dim AS d, "+ 
       "adj_dim AS adj " + 
       "cam_dim AS cam, " + 
       "agg_day_adv_campaign_demand_fact AS fact "; 

    Pattern FACT_PAT = Pattern.compile("(\\S+_fact)"); 
    Matcher m = FACT_PAT.matcher(text); 
    if (m.find()){ 
     System.out.println(m.group(1)); 
    } 
+0

謝謝JosefN。上面的代碼只打印正則表達式,即_fact。但要求打印完整的單詞。 – user3110457

+0

我修好了:),對不起 – JosefN

0

你可以簡單地split串入詞和檢查字一個一個以搜索爲你的模式。

3

正則表達式\ W * _fact會做到這一點。 你可以在這裏測試這個表達式(http://regexpal.com/

import java.util.regex.Matcher; 
import java.util.regex.Pattern; 

public class Main { 

    public static void main(String[] args) { 
     String text = 
       "FROM dt_dim AS d, "+ 
         "adj_dim AS adj " + 
         "cam_dim AS cam, " + 
         "agg_day_adv_campaign_demand_fact AS fact "; 
     Pattern pattern = Pattern.compile("\\w*_fact"); 
     Matcher matcher = pattern.matcher(text); 
     while (matcher.find()) { 
      System.out.println("Found the text " + matcher.group()+ "starting at " + matcher.start() 
        + " index and ending at index " + matcher.end()); 
      System.out.println(text.substring(matcher.start(), matcher.end())); 
     } 
    } 
}