马彻:“找不到比赛......”

时间:2013-12-01 17:47:29

标签: java regex matcher

我在匹配器中收到错误,说“找不到匹配项”     在java.util.regex.Matcher.group(Matcher.java:468)“。

我的评论代码如下。我一直在改变m.group中的数字,所以我现在怀疑我的正则表达式。 Archetype是这样一个字符串:#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;

1 个答案:

答案 0 :(得分:4)

你的问题是你在尝试获得小组之前从未打过电话,这就是为什么你没有匹配。

你需要这行代码:

m.find();

在你做之前

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

但是即使这样,你也可以使用哈希标签来解决这个问题,以避免你应该为围绕哈希标签的内部文本创建组,如下所示:

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

当您访问您的组时,它将是组号1(因为0是整个模式)。所以改变这样的组:

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