Java实现文本中的关键字高亮,匹配所有长度

这个方法还不完整,后面想起来再看,直接放代码.

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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
public
static
String
getHeightlightWord
(String textWord, String key)
{
StringBuffer
sb
=
new
StringBuffer
(
""
);
String
tempWord
=
textWord ==
null
?
""
: textWord.trim();
String
tempKey
=
key ==
null
?
""
: key.trim();
if
(
""
.equals(tempWord) ||
""
.equals(tempKey)){
return
tempWord;
}
else
{
sb.append(tempWord);
}
String
upperWord
=
tempWord.toUpperCase();
String
upperKey
=
tempKey.toUpperCase();
if
(!upperWord.contains(upperKey)){
return
tempWord;
}
else
{
int
keyLen
=
upperKey.length();
int
thisMathIndex
=
;
List<Map<Integer, String>> matchList =
new
ArrayList
<Map<Integer, String>>();
while
((thisMathIndex = upperWord.indexOf(upperKey, thisMathIndex)) != -
){
Map<Integer, String> map =
new
HashMap
<Integer, String>();
map.put(thisMathIndex, tempWord.substring(thisMathIndex, thisMathIndex + keyLen));
matchList.add(map);
thisMathIndex += keyLen;
}
int
thisKey
=
;
int
keys
=
;
for
(Map<Integer, String> map : matchList){
thisKey = getKey(map);
keys += thisKey;
sb.replace(thisKey, thisKey + keyLen,
"<span style='background-color: yellow;'>"
+map.get(thisKey)+
"</span>"
);
keys +=
"<span style='background-color: yellow;'></span>"
.length();
}
}
return
sb.toString();
}
private
static
int
getKey
(Map<Integer, String> obj)
{
Set<Integer> keySet = obj.keySet();
int
firstKey
=
-
;
for
(
int
key : keySet){
firstKey = key;
if
(firstKey != -
){
break
;
}
}
return
firstKey;
}

以上代码可实现一次高亮,余下的问题就在于如何多次改变字符串的长度后能定位到需要更改的字符串(即多次高亮),打个卡先,有空再弄


Java实现文本中的关键字高亮,匹配所有长度
https://zhouyinglin.top/2022/08/06/Java实现文本中的关键字高亮,匹配所有长度/
作者
小周
发布于
2022年8月6日
许可协议