简体   繁体   English

您如何创建数组以在Java中存储正则表达式字符串匹配?

[英]How do you create an array to store regex string matches in java?

I'm trying to take a file that store data of this form: 我正在尝试获取一个存储这种形式的数据的文件:

Name=”Biscuit”

LatinName=”Retrieverus Aurum”

ImageFilename=”Biscuit.png”

DNA=”ITAYATYITITIAAYI”

and read it with a regex to locate the useful information; 并使用正则表达式进行阅读以找到有用的信息; namely, the fields and their contents. 即字段及其内容。

I have created the regex already, but I can only seem to get one match at any given time, and would like instead to put each of the matches from each line in the file in their own index of a string. 我已经创建了正则表达式,但是在任何给定时间我似乎只能得到一个匹配项,而是想将文件中每一行的每个匹配项放在它们自己的字符串索引中。

Here's what I have so far: 这是我到目前为止的内容:

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;

Thanks so much for your help! 非常感谢你的帮助!

I hope I understand your question correctly... Here is an example that is coming from the Oracle website: 希望我能正确理解您的问题...这是一个来自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());
    }
}

Hope this helps... 希望这可以帮助...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM