Question

I'm getting an error in matcher saying "No match found at java.util.regex.Matcher.group(Matcher.java:468)".

My commented code's below. I've been changing the number within m.group, so I now suspect something's up with my regex. Archetype's a string like this: We #plan_to# #deliver# #highly_effective# #esolutions# for today's #data_driven# #market_leaders#.

List<String> phraseCollection = parserHelper.getPhrases(fileKontent,"phrases:");
    String archetype = parserHelper.getRandomElement(phraseCollection);
    boolean flagga = true;
    while(flagga == true){
    Pattern ptrn = Pattern.compile("#[^#]+#");
    Matcher m = ptrn.matcher(archetype);
    String fromMatcher = m.group(0);//first word surrounded by hash, without the hash
    String col = ":";
    String token = fromMatcher+col;//token to pass to getPhrase
    List<String> pCol = parserHelper.getPhrases(fileKontent, token);
    String repl = parserHelper.getRandomElement(pCol); //new word to replace with
    String hash = "#";
    String tk2 = hash + fromMatcher + hash;  //word surrounded by hash to be replaced, hash and all
    archetype = parserHelper.replace(archetype, tk2, repl);  //now archetype should have 1 less hashed word
    flagga = m.find();  //false when all hash gone
    }
    String theArcha = archetype;

    return theArcha;
Was it helpful?

Solution

Your problem is that you never call find before trying to get group, that is why you don't have match.

You need this line of code:

m.find();

Before you do

String fromMatcher = m.group(0); //first word surrounded by hash, without the hash

But even then, you will get it all with hash tags around, to avoid that you should create group only for inner text around hash tags like this:

 Pattern ptrn = Pattern.compile("#([^#]+)#");

And when you are accessing your group it will be group number 1 (because 0 is whole pattern). So change getting group like this:

String fromMatcher = m.group(1); //first word surrounded by hash, without the hash
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top