質問

私の仕事は、英語の無期限の記事を認識する正規表現、つまり「a」または「an」という言葉を考案することです。約10行のテキストを含むファイルを読み取るテストドライバーを作成して、式をテストする必要があります。あなたのプログラムは、「a」と「an」という言葉の出現を数える必要があります。an.

これはこれまでの私のコードです:

import java.io.IOException;
import java.util.Arrays;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class RegexeFindText {
   public static void main(String[] args) throws IOException {

      // Input for matching the regexe pattern
       String file_name = "Testing.txt";

           ReadFile file = new ReadFile(file_name);
           String[] aryLines = file.OpenFile();  
           String asString = Arrays.toString(aryLines);

            // Regexe to be matched
               String regexe = ""; //<<--this is where the problem lies

           int i;
           for ( i=0; i < aryLines.length; i++ ) {
           System.out.println( aryLines[ i ] ) ;
           }


      // Step 1: Allocate a Pattern object to compile a regexe
      Pattern pattern = Pattern.compile(regexe);
      //Pattern pattern = Pattern.compile(regexe, Pattern.CASE_INSENSITIVE);  
      // case-        insensitive matching

      // Step 2: Allocate a Matcher object from the compiled regexe pattern,
      //         and provide the input to the Matcher
      Matcher matcher = pattern.matcher(asString);

      // Step 3: Perform the matching and process the matching result

      // Use method find()
      while (matcher.find()) {     // find the next match
         System.out.println("find() found the pattern \"" + matcher.group()
               + "\" starting at index " + matcher.start()
               + " and ending at index " + matcher.end());
      }

      // Use method matches()
      if (matcher.matches()) {
         System.out.println("matches() found the pattern \"" + matcher.group()
               + "\" starting at index " + matcher.start()
               + " and ending at index " + matcher.end());
      } else {
         System.out.println("matches() found nothing");
      }

      // Use method lookingAt()
      if (matcher.lookingAt()) {
         System.out.println("lookingAt() found the pattern \"" + matcher.group()
               + "\" starting at index " + matcher.start()
               + " and ending at index " + matcher.end());
      } else {
         System.out.println("lookingAt() found nothing");
      }
   }
}

私の質問は、単に私のテキスト内のそれらの単語を見つけるために何を使用する必要があるかということです。どんな助けでも大歓迎です、ありがとう!

役に立ちましたか?

解決

これが「a」または「an」に一致する正規表現です:

String regex = "\\ban?\\b";

その正規表現を破りましょう:

  • \b 単語境界を意味します(単一のバックスラッシュは次のように書かれています "\\" Javaで)
  • a 単に文字通りです "a"
  • n? ゼロまたは1つのリテラルを意味します "n"
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top