我正在尝试检查字符串是否有超过2次的特殊字符 我使用以下代码从List获得的字符串:
List <String> lst;
for(String str: lst)
{
System.out.println(str);
}
说输入示例:
This is sample example.
########################
This will help you for sure
"my friend" do not ask to delay more.
$$200 not much
sssssss
better to go home.
我希望输出像这样:
This is sample example.
This will help you for sure
"my friend" do not ask to delay more.
$$200 not much
better to go home.
如何使用JAVA实现此输出?请建议一种方式。
答案 0 :(得分:1)
试试这个正则表达式:
string.replaceAll("^.*[._\'!#$%&*+\\\\/=?{|}~\\^-]{2}.*$", "");
答案 1 :(得分:-1)
创建一个char数组并搜索每个字符以查看是否出现3个特殊字符,如果是这样的话(或者在我的情况下,不要将该字符串复制到将用于打印的newList。我没有删除ssssssss字符串,因为它不是特殊字符,但如果你做了一个额外的if并检查3个连续字符是否具有相同的值,你也可以这样做。
public static void main(String[] args) {
List <String> lst = new ArrayList<>();
List <String> newList = new ArrayList<>();
lst.add("This is sample example.");
lst.add("########################");
lst.add("This will help you for sure");
lst.add("\"my friend\" do not ask to delay more.");
lst.add("$$200 not much");
lst.add("sssssss");
lst.add("better to go home.");
for(int i = 0; i < lst.size(); i++) {
boolean keep = true;
char[] c = lst.get(i).toCharArray();
for(int j = 0; j < c.length; j++) {
//the following line can be edited based on what you consider special characters
//但这将允许所有数字和字母
if(j+2 < c.length && (c[j] < 48 || c[j] > 122 ||(c[j] > 57 && c[j] < 65))) {
if(c[j+1] < 65 || c[j+1] > 122 ||(c[j] > 57 && c[j] < 65)) {
if(c[j+2] < 65 || c[j+2] > 122 ||(c[j] > 57 && c[j] < 65)) {
keep = false;
}
}
}
}
if(keep) {
newList.add(lst.get(i));
}
}
for(String str: newList)
{
System.out.println(str);
}
}