【问题标题】:How do you create an array to store regex string matches in java?如何在 java 中创建一个数组来存储正则表达式字符串匹配?
【发布时间】:2010-09-09 22:25:36
【问题描述】:

我正在尝试获取存储此表单数据的文件:

Name=”Biscuit”

LatinName=”Retrieverus Aurum”

ImageFilename=”Biscuit.png”

DNA=”ITAYATYITITIAAYI”

并使用正则表达式读取它以找到有用的信息;即字段及其内容。

我已经创建了正则表达式,但我似乎只能在任何给定时间获得一个匹配项,并且希望将文件中每一行的每个匹配项放在他们自己的字符串索引中。

这是我目前所拥有的:

Scanner scanFile = new Scanner(file); 
        while (scanFile.hasNextLine()){
            System.out.println(scanFile.findInLine(".*"));
            scanFile.nextLine();
        }
        MatchResult result = null;
        scanFile.findInLine(Constants.ANIMAL_INFO_REGEX);
        result = scanFile.match();


        for (int i=1; i<=result.groupCount(); i++){
            System.out.println(result.group(i));
            System.out.println(result.groupCount());
        }
        scanFile.close();
        MySpecies species = new MySpecies(null, null, null, null);
        return species;

非常感谢您的帮助!

【问题讨论】:

标签: java regex arrays java.util.scanner


【解决方案1】:

希望我能正确理解您的问题...这是来自 Oracle 网站的示例:

/*
 * This code writes "One dog, two dogs in the yard."
 * to the standard-output stream:
 */
import java.util.regex.*;

public class Replacement {
    public static void main(String[] args) 
                         throws Exception {
        // Create a pattern to match cat
        Pattern p = Pattern.compile("cat");
        // Create a matcher with an input string
        Matcher m = p.matcher("one cat," +
                       " two cats in the yard");
        StringBuffer sb = new StringBuffer();
        boolean result = m.find();
        // Loop through and create a new String 
        // with the replacements
        while(result) {
            m.appendReplacement(sb, "dog");
            result = m.find();
        }
        // Add the last segment of input to 
        // the new String
        m.appendTail(sb);
        System.out.println(sb.toString());
    }
}

希望这会有所帮助...

【讨论】:

  • 不,这根本不适用。
猜你喜欢
  • 1970-01-01
  • 2012-03-25
  • 1970-01-01
  • 1970-01-01
  • 2012-02-20
  • 2019-09-10
  • 1970-01-01
  • 2013-10-14
  • 1970-01-01
相关资源
最近更新 更多