开发者

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开发者_如何学JAVA, 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:

/*
 * 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...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜