0

この種の文字列で場所の名前(例ではサンアントニオですが、何でもかまいません)を見つける必要があります

  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. 開始 () = 0、終了 () = 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"
    

文が常に都市名で終わっている場合、問題は簡単に修正できます。「in」という単語を探し、残りは都市名です。しかし、問題は、文 2 で「明日」が存在するかどうか、およびそれを都市名グループから削除する方法を理解できない場合です。

正規表現のテストには、このページを使用しています

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

手伝ってくれてありがとう。

4

1 に答える 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"
    
于 2013-04-15T22:02:22.340 に答える