문제

I have written code in Java to return a string of information in between two sequences of characters. My code is:

String caseDefendant = "vs."; 
Pattern caseDefendantPattern = Pattern.compile("(?<="+Pattern.quote(caseDefendant)+").*?(?=</span>)");
Matcher caseDefendantMatcher = caseDefendantPattern.matcher(pageContentString); 

while (caseDefendantMatcher.find()) {
    docketFile.write(caseDefendantMatcher.group().toString()); 
}
docketFile.write("^");

What I am trying to do is return the information in between vs. and </span>. This issue is that in the string "pageContentString" the sequence vs.INFORMATION</span> occurs twice, so when I go to write it to the file it is written twice instead of once, when I only need the information written once. For instance, If the pageContentString was:

"vs.info1</span>   aaabbbccc vs.info1</span>" 

My file is written as info1 info1. How would I change my code so it would not write the second group of information?

도움이 되었습니까?

해결책

You have a loop here:

while (caseDefendantMatcher.find()) {
    docketFile.write(caseDefendantMatcher.group().toString()); 
}

This loop will find and print all the matches. If you only want the first match then don't loop:

String caseDefendant = "vs."; 
Pattern caseDefendantPattern = Pattern.compile("(?<="+Pattern.quote(caseDefendant)+").*?(?=</span>)");
Matcher caseDefendantMatcher = caseDefendantPattern.matcher(pageContentString); 

if (caseDefendantMatcher.find()) {
    docketFile.write(caseDefendantMatcher.group().toString()); 
}

docketFile.write("^");
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top