正则表达式放置?要么 !如果在原始单词中检测到

时间:2016-02-24 13:30:20

标签: java regex

我有一个Stemmer函数,如果它在原始单词中检测到一个句点,它将返回词干并放置句点。

这是代码:

static String stemWord(Stemmer s, String word) throws Exception
{
    return s.StemWordWithWordNet(word)
    + (word.charAt(word.length()-1) == '.'?"?":"" );
}

因此,当我在stemWord函数中输入一个单词时,如果在原始单词中检测到1,则会在单词的末尾放置一个点。实施例

placing. -> place.  //notice it place a dot if it detects a dot in the original word
ate -> ate //no dot

现在我如何修改正则表达式以便放置一个?要么 !如果它检测到一个。

going? -> go?
reading! -> read!

1 个答案:

答案 0 :(得分:3)

您可以使用包含一组有效的结束标点符号的正则表达式,并将其复制到词干上:

private static final Pattern PUNCTUATION_PATTERN = Pattern.compile("[.?!]$");

static String stemWord(Stemmer s, String word) throws Exception {
    String word = "testing.";
    String stem = s.StemWordWithWordNet(word);

    Matcher m = PUNCTUATION_PATTERN.matcher(word);
    String endingPunctuation = m.find() ? m.group() : "";

    return stem + endingPunctuation;
}