gpt4 book ai didi

java - Java 中的正则表达式将匹配项存储到 ArrayList 中

转载 作者:行者123 更新时间:2023-12-01 12:58:22 25 4
gpt4 key购买 nike

我编写了以下代码,目的是存储和显示以字母 a 开头并以 z 结尾的所有单词。首先,我从正则表达式模式中收到错误,其次,我从不显示存储到 ArrayList 中的内容(字符串)中收到错误。

import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.regex.*;


public class RegexSimple2{

public static void main(String[] args) {
try{
Scanner myfis = new Scanner("D:\\myfis2.txt");
ArrayList <String> foundaz = new ArrayList<String>();
while(myfis.hasNext()){
String line = myfis.nextLine();
String delim = " ";
String [] words = line.split(delim);
for ( String s: words){
if(!s.isEmpty()&& s!=null){
Pattern pi = Pattern.compile("[a|A][a-z]*[z]");
Matcher ma = pi.matcher(s);
boolean search = false;
while (ma.find()){
search = true;
foundaz.add(s);
}
if(!search){
System.out.println("Words that start with a and end with z have not been found");
}
}
}
}

if(!foundaz.isEmpty()){
for(String s: foundaz){
System.out.println("The word that start with a and ends with z is:" + s + " ");
}
}
}
catch(Exception ex){
System.out.println(ex);
}
}
}

最佳答案

您需要更改读取文件的方式。此外,将正则表达式更改为 [aA].*z.* 匹配零个或多个任何内容。请参阅下面我所做的细微更改:

import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.regex.*;

public class Test {

public static void main(String[] args) {

try {
BufferedReader myfis = new BufferedReader(new FileReader("D:\\myfis2.txt"));
ArrayList<String> foundaz = new ArrayList<String>();

String line;
while ((line = myfis.readLine()) != null) {
String delim = " ";
String[] words = line.split(delim);

for (String s : words) {
if (!s.isEmpty() && s != null) {
Pattern pi = Pattern.compile("[aA].*z");
Matcher ma = pi.matcher(s);

if (ma.find()) {
foundaz.add(s);
}
}
}
}

if (!foundaz.isEmpty()) {
System.out.println("The words that start with a and ends with z are:");
for (String s : foundaz) {
System.out.println(s);
}
}
} catch (Exception ex) {
System.out.println(ex);
}
}
}

输入是:

apple
applez
Applez
banana

输出为:

The words that start with a and ends with z are:
applez
Applez

关于java - Java 中的正则表达式将匹配项存储到 ArrayList 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23713442/

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