Regex - распознавать неопределенный артикль "a" или "an" с помощью JAVA - PullRequest
2 голосов
/ 22 февраля 2012

Моя задача - разработать регулярное выражение, которое распознает неопределенную статью на английском языке - слово «a» или «an», т. Е. Написать регулярное выражение для идентификации слова a или слова an.Я должен проверить выражение, написав тестовый драйвер, который читает файл, содержащий примерно десять строк текста.Ваша программа должна считать вхождения слов «a» и «an». Я не должен совпадать с символами a и a в таких словах, как th 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");
      }
   }
}

У меня просто вопрос, что мне нужно использовать, чтобы найти эти слова в моем тексте?Любая помощь будет высоко ценится, спасибо!

1 Ответ

3 голосов
/ 22 февраля 2012

Вот регулярное выражение, которое будет соответствовать «a» или «an»:

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

Давайте разберем это регулярное выражение:

  • \b означает границу слова (одинобратная косая черта записывается как "\\" в Java)
  • a - это просто литерал "a"
  • n? означает ноль или один литерал "n"
...