-
Notifications
You must be signed in to change notification settings - Fork 46
Expand file tree
/
Copy pathContentsUtils.java
More file actions
58 lines (47 loc) · 2.1 KB
/
ContentsUtils.java
File metadata and controls
58 lines (47 loc) · 2.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package org.ayfaar.app.utils.contents;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Component
public class ContentsUtils {
public static String filterLengthWordsAfter(String paragraph, String search, int countWordsBeforeAndAfter){
String wholeFind = "";
String searchResult = null;
String str = paragraph;
String find = search;
//check if not the full text
Pattern pattern = Pattern.compile("\\S*" + find + "\\S*",Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
wholeFind = matcher.group();
}
//create minimal string
int countWords = countWordsBeforeAndAfter;
String[] sp = str.split(" +"); // "+" for multiple spaces
List<String> strings = Arrays.asList(sp);
String[] findStringArr = {};
if (wholeFind.equals("")) findStringArr = find.split(" ");
else findStringArr = wholeFind.split(" ");
int lengthFindStringArr = findStringArr.length;
int lengthParagraph = sp.length;
String firstPosition = findStringArr[0];
String lastPosition = findStringArr[lengthFindStringArr - 1];
int iLast = strings.indexOf(lastPosition);
for (int i = 0; i < lengthParagraph; i++) {
String addFirstDots = "";
if (sp[i].equals(firstPosition) && sp[i + lengthFindStringArr-1].equals(lastPosition)) {
String after = "";
for (int j = 1; j <= countWords; j++) {
if(iLast+j < lengthParagraph) after += " " + sp[iLast+j];
}
after = after.replaceAll("[-+.^:,]$","");
if(!after.equals(" ") && iLast + countWords < lengthParagraph) after += "...";
if (!firstPosition.equals(sp[0])) addFirstDots = "...";
searchResult = addFirstDots + wholeFind + after;
}
}
return searchResult == null ? "" : searchResult;
}
}