regex 在Java中自动解释句子

jhkqcmku  于 11个月前  发布在  Java
关注(0)|答案(1)|浏览(107)

在Java中,我尝试使用正则表达式自动解释文本。
因此,我需要找到一种方法,将正则表达式的第一个匹配替换为该正则表达式的随机生成的匹配,如下所示:

public static String paraphraseUsingRegularExpression(String textToParaphrase, String regexToUse){
    //In textToParaphrase, replace the first match of regexToUse with a randomly generated match of regexToUse, and return the modified string.
}

字符串
那么,如何将字符串中正则表达式的第一个匹配项替换为该正则表达式的随机生成的匹配项呢?(也许一个名为xeger的库可以用于此目的。)
例如,paraphraseUsingRegularExpression("I am very happy today", "(very|extremely) (happy|joyful) (today|at this (moment|time|instant in time))");将用正则表达式的随机生成的匹配替换正则表达式的第一个匹配,这可能会产生输出"I am extremely joyful at this moment in time""I am very happy at this time"

3vpjnl9f

3vpjnl9f1#

你可以通过下面的步骤来实现:
首先,用regexToUse拆分textToParaphrase字符串,您将得到一个数组,其中textToParaphrase的部分与提供的表达式不匹配。例如:如果,

textToParaphrase = "I am very happy today for you";
 regexToUse = "(very|extremely) (happy|joyful) (today|at this (moment|time|instant in time))";

字符串
输出将为:{"I am ", "for you"}。然后用这些生成的字符串创建一个正则表达式(如"(I am |for you)")。现在再次用这个生成的表达式拆分textToParaphrase,你将得到给定正则表达式的匹配部分的数组。最后用随机生成的字符串替换每个匹配部分。
代码如下:

public static String paraphraseUsingRegularExpression(String textToParaphrase, String regexToUse){
    String[] unMatchedPortionArray = textToParaphrase.split(regexToUse);
    String regExToFilter = "(";
    for(int i = 0; i< unMatchedPortionArray.length; i++){
        if(i == unMatchedPortionArray.length -1){
            regExToFilter+=unMatchedPortionArray[i];
        } else {
            regExToFilter+=unMatchedPortionArray[i]+"|";
        }
    }
    regExToFilter+=")";

    String[] matchedPortionArray = textToParaphrase.split(regExToFilter);
    Xeger generator = new Xeger(regexToUse);
    for (String matchedSegment : matchedPortionArray){
    String result = generator.generate(); //generates randomly (according to you!)
        textToParaphrase = textToParaphrase.replace(matchedSegment, result);
    }
    return textToParaphrase;
}


干杯!干杯!

相关问题