gpt4 book ai didi

java - 如何识别不定冠词 "a"或 "an"?

转载 作者:行者123 更新时间:2023-12-04 05:57:02 24 4
gpt4 key购买 nike

我的任务是设计一个正则表达式来识别英语中的不定冠词——单词“a”或“an”,即编写一个正则表达式来识别单词 a 或单词 an。我必须通过编写一个测试驱动程序来测试表达式,该驱动程序读取一个包含大约十行文本的文件。您的程序应该计算单词“a”和“an”的出现次数。 I 将不匹配字符 a 和 an 在诸如 th 之类的单词中 .
到目前为止,这是我的代码:

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?表示零或一个文字 "n"
  • 关于java - 如何识别不定冠词 "a"或 "an"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9401866/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com