[英]Remove a set of special character from a String
我需要從字符串中刪除一組特殊字符(即[]'?!+-.,
)。 典型的排他性解決方案replaceAll("[^a-zA-Z0-9]", "")
不合適,因為我只需要刪除這些字符,並保存包含希臘字符的文本。 例如:
public static void test_regex() {
ArrayList<String> tests = new ArrayList<>();
tests.add("------.");
tests.add("+[---].");
tests.add("------?");
tests.add("---]〛");
tests.add("A++[---].");
tests.add("AV[---]S");
for (String s : tests) {
String becomes = s.replaceAll("[.-\\\\,]", "");
System.out.println(s + " becomes <" + becomes + ">");
}
}
應該給作為輸出
------. becomes <>
+[---]. becomes <>
------? becomes <>
---]〛 becomes <>
A++[---]. becomes <A>
AV[---] becomes <AV>
但是我不能。 我成功移除.
和-
與[.-]
,但隨后我添加\\\\[
並破壞了所有內容(也嘗試了\\\\\\\\[
或\\\\\\\\\\\\[
)),也\\\\\\\\\\\\[
.
在工作之前不再工作了。
哪種方法可以逃脫這些角色中的每個角色?
您可以使用以下正則表達式替換來擺脫所有不需要的字符:
String becomes = s.replaceAll("[ \\]\\[.\\\\,+?-]+", "");
[, ], +, ?, |
等你的角色課。 +
以獲得更好的性能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.