Java 返回文本中给定位置前后的指定字数

Java 返回文本中给定位置前后的指定字数,java,regex,words,Java,Regex,Words,下面的代码有一个大问题。我希望它在找到的关键字(针)前后返回n个单词,但它从来没有返回过 如果我有短信,说 "There is a lot of interesting stuff going on, when someone tries to find the needle in the haystack. Especially if there is anything to see blah blah blah". 我有一个正则表达式: "((?:[a-zA-Z'-]+[^a-zA-Z'

下面的代码有一个大问题。我希望它在找到的关键字(针)前后返回n个单词,但它从来没有返回过

如果我有短信,说

"There is a lot of interesting stuff going on, when someone tries to find the needle in the haystack. Especially if there is anything to see blah blah blah". 
我有一个正则表达式:

"((?:[a-zA-Z'-]+[^a-zA-Z'-]+){0,5}\b)needle(\b(?:[^a-zA-Z'-]+[a-zA-Z'-]+){0,5})"
这是否应该与给定字符串中的指针不完全匹配,并将文本返回为

someone tries to find the needle in the haystack. Especially if
它从来不会:-(在执行时,我的方法总是返回一个空字符串,尽管我肯定知道关键字在给定的文本中

private String trimStringAtWordBoundary(String haystack, int wordsBefore, int wordsAfter, String needle) {
    if(haystack == null || haystack.trim().isEmpty()){
        return haystack ;
    }

    String textsegments = "";

    String patternString = "((?:[a-zA-Z'-]+[^a-zA-Z'-]+){0,"+wordsBefore+"}\b)" + needle + "(\b(?:[^a-zA-Z'-]+[a-zA-Z'-]+){0,"+wordsAfter+"})";


    Pattern pattern = Pattern.compile(patternString);
    Matcher matcher = pattern.matcher(haystack);

    logger.trace(">>> using regular expression: " + matcher.toString());

    while(matcher.find()){
        logger.trace(">>> found you between " + matcher.regionStart() + " and " + matcher.regionEnd());
        String segText = matcher.group(0); // as well tried it with group(1)
        textsegments += segText + "...";
    }

    return textsegments;
}

很明显,这个问题存在于我的正则表达式中,但我无法找出它的错误所在。

您的正则表达式基本上没有问题,但在Java中,您需要避开
\b

"((?:[a-zA-Z'-]+[^a-zA-Z'-]+){0,5}\\b)needle(\\b(?:[^a-zA-Z'-]+[a-zA-Z'-]+){0,5})"

看起来您并没有在表达式中设置空格字符,通常您会在有
\b
的地方使用
\s
,并且在它前面/后面的字符类中也使用它…类似于
“(((?:[\w'\.-]+\s){0,+wordsBefore+“})”
和后面的类似…也许我遗漏了一些东西,但是
\\b
真的解释了空白吗?我想还必须有一个
\\s
存在…\b是单词边界元字符,所以它比空格匹配多一点。好的,但是不是每个分隔都必须有两个边界吗n单词之间?
\\b
实际上并不匹配两个单词之间所有可能的空白,是吗,因为它被指定为“零宽度匹配”?它会吃掉两个单词之间所有可能的空格。我想这正是零宽度匹配的意思。哈哈,是的,这是为你编程的。我们都去过那里。