匹配最小可能组java regexp
我正试图找出如何让这个正则表达式以我需要的方式正常工作。基本上我有一大堆歌词。我循环浏览每首歌曲的歌词,看看它们是否匹配我要查找的搜索短语,并返回字符串的长度,就像匹配评级一样 例如,我这里有一首歌的部分歌词:匹配最小可能组java regexp,java,regex,Java,Regex,我正试图找出如何让这个正则表达式以我需要的方式正常工作。基本上我有一大堆歌词。我循环浏览每首歌曲的歌词,看看它们是否匹配我要查找的搜索短语,并返回字符串的长度,就像匹配评级一样 例如,我这里有一首歌的部分歌词: "you gave up the love you got & that is that she loves me now she loves you not and that where its at" 我正在使用此regexp查找匹配项: (?mi)(\bShe\b)
"you gave up the love you got & that is that
she loves me now she loves you not and that where its at"
我正在使用此regexp查找匹配项:
(?mi)(\bShe\b).*(\bloves\b).*(\byou\b)
然而,它抓住了这个群体
"she loves me now she loves you"
我想抓住可能最小的群体,那就是“她爱你”
我如何才能使这次捕获成为可能的最小组
下面是我的一些代码,我把这个短语拆分成一个数组,然后检查歌词是否包含这个词,否则我们可以退出。然后我构建一个字符串,它将成为正则表达式
static int rankPhrase(String lyrics, String lyricsPhrase){
//This takes in song lyrics and the phrase we are searching for
//Split the phrase up into separate words
String[] phrase = lyricsPhrase.split("[^a-zA-Z]+");
//Start to build the regex
StringBuilder regex = new StringBuilder("(?im)"+"(\\" + "b" + phrase[0] + "\\b)");
//loop through each word in the phrase
for(int i = 1; i < phrase.length; i++){
//Check to see if this word exists in the lyrics first
if(lyrics.contains(phrase[i])){
//add this to the regex we will search for
regex.append(".*(\\b" + phrase[i] + "\\b)");
}else{
//if the song isn't found return the rank of
//-1 this means song doesn't contain phrase
return -1;
}
}
//Create the pattern
Pattern p = Pattern.compile(regex.toString());
Matcher m = p.matcher(lyrics);
//Check to see if it can find a match
if(m.find()){
//Store this match in a string
String match = m.group();
static int rankPhrase(字符串歌词、字符串歌词短语){
//这需要在歌词和短语,我们正在寻找
//把短语分成几个单独的词
字符串[]短语=抒情短语。拆分([^a-zA-Z]+”;
//开始构建正则表达式
StringBuilder正则表达式=新的StringBuilder(“(?im)”+”(\\“+”b“+短语[0]+“\\b”);
//循环浏览短语中的每个单词
for(int i=1;i
Java的正则表达式匹配器只在前进方向工作。您需要做的是迭代找到的所有匹配集,并选择最短的一个
(\bShe\b)(?:(?!\b(?:she|loves|you)\b).)*(\bloves\b)(?:(?!\b(?:she|loves|you)\b).)*(\byou\b)
您可以在此处使用lookahead
。请参阅演示
对于java,使用
(\\bShe\\b)(?:(?!\\b(?:she|loves|you)\\b).)*(\\bloves\\b)(?:(?!\\b(?:she|loves|you)\\b).)*(\\byou\\b)
这里你需要使用负前瞻
Pattern.compile("\\bShe\\b(?:(?!\\bshe\\b).)*?\\bloves\\b(?:(?!\\b(?:you|loves)\\b).)*\\byou\\b");
捕获所有匹配的组并选择最小的组?您应该使用2-3个示例更新您的问题,显示您正试图捕获的内容。还请包含相关的Java代码。谢谢,我添加了一些代码,如果它有助于实现senseThanks,我将尝试一下,在测试工具中看起来很棒。唯一的我遇到的问题是,它似乎没有多行,我有“im”标志\n@CJWeber使用
s
标志或使用[\s\s]