2013-04-15 62 views
0

我需要找到一個地方的名稱(聖安東尼奧的例子,但可以不管)在這種字符串查找未知子與正則表達式其他已知的(但可選)字符串之間的Java

  1. 天氣怎麼在聖安東尼奧
  2. 會有什麼天氣在聖安東尼奧的明天
  3. 會是怎樣的天氣,明天在聖安東尼奧

這個JAVA正則表達式:

(What's|What is|What will be) the weather(tomorrow)?(in (\D*))? 

我得到分別爲:

  1. 開始()= 0,結束()= 33

    group(0) = "What's the weather in San Antonio" 
    
    group(1) = "What's" 
    
    group(2) = "null" 
    
    group(3) = " in San Antonio" 
    
    group(4) = "San Antonio" 
    
  2. 開始()= 0,結束()= 48

    group(0) = "What will be the weather in San Antonio tomorrow" 
    
    group(1) = "What will be" 
    
    group(2) = "null" 
    
    group(3) = " in San Antonio tomorrow" 
    
    group(4) = "San Antonio tomorrow" 
    
  3. start()= 0,end()= 48

    group(0) = "What will be the weather tomorrow in San Antonio" 
    
    group(1) = "What will be" 
    
    group(2) = " tomorrow" 
    
    group(3) = " in San Antonio" 
    
    group(4) = "San Antonio" 
    

如果句子與城市名稱本身的問題可以很容易地固定總是能完成,我期待已久「的」字和仍然是城市的名稱。 但問題是,在句子2中我無法理解「明天」是否存在以及如何將其從城市名稱組中刪除。

對於正則表達式測試我使用這個頁面

http://www.cis.upenn.edu/~matuszek/General/RegexTester/regex-tester.html

感謝您的幫助。

+1

看起來你甚至不需要爲這個正則表達式... –

回答

2

下應該爲所有的測試串的工作:

(What's|What is|What will be) the weather(tomorrow)?(in (\D*?)(tomorrow)?$)? 

新結果(第4組永遠是城市):

  1. 是什麼在聖安東尼奧

    天氣
    start() = 0, end() = 33 
    group(0) = "What's the weather in San Antonio" 
    group(1) = "What's" 
    group(2) = "null" 
    group(3) = " in San Antonio" 
    group(4) = "San Antonio" 
    group(5) = "null" 
    
  2. 明天聖安東尼奧天氣怎麼樣

    start() = 0, end() = 48 
    group(0) = "What will be the weather in San Antonio tomorrow" 
    group(1) = "What will be" 
    group(2) = "null" 
    group(3) = " in San Antonio tomorrow" 
    group(4) = "San Antonio" 
    group(5) = " tomorrow" 
    
  3. 什麼將是明天的天氣在聖安東尼奧

    start() = 0, end() = 48 
    group(0) = "What will be the weather tomorrow in San Antonio" 
    group(1) = "What will be" 
    group(2) = " tomorrow" 
    group(3) = " in San Antonio" 
    group(4) = "San Antonio" 
    group(5) = "null" 
    
+0

似乎很有道理,我會測試它更好的下一天。實際上,這個解決方案可以應用於許多其他應用,不僅適用於天氣或聖安東尼奧!謝謝! –

相關問題