![](/img/trans.png)
[英]in java using regex how can i find last 3 words from a position in string
[英]How can I find multiple words in Java regex
我想檢查禁止詞。
用我的代碼
public static String filterText(String sText) {
Pattern p = Pattern.compile("test", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(sText);
StringBuffer buf = new StringBuffer();
while (m.find()){
m.appendReplacement(buf, maskWord(m.group()));
}
m.appendTail(buf);
return buf.toString();
}
public static String maskWord(String str) {
StringBuffer buf = new StringBuffer();
char[] ch = str.toCharArray();
for (int i = 0; i < ch.length; i++) {
buf.append("*");
}
return buf.toString();
}
如果您收到句子“ test is test”,則使用以上代碼將其表示為“ **** is ****”。
但是我想過濾掉至少幾十到幾百個單詞。
單詞存儲在數據庫中。(數據庫類型:Oralce)
那么,如何檢查多個單詞呢?
假設您使用的是Java 9,則可以使用Matcher.replaceAll
替換一條語句中的單詞。 您還可以使用String.replaceAll
將每個字符替換為'*'。
模式中可以包含許多替代方案。 您可以使用所有需要的單詞來構造一個模式。
Pattern pattern = Pattern.compile("(word1|word2|word3)");
String result = pattern.matcher(input)
.replaceAll(w -> w.group(1).replaceAll(".", "*"));
另外,您可以列出一個模式,然后依次替換每個模式:
for (Pattern pattern: patternList)
result = pattern.matcher(result)
.replaceAll(w -> w.group(1).replaceAll(".", "*"));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.