Home >Java >javaTutorial >Java uses regular expressions to remove English from strings

Java uses regular expressions to remove English from strings

php是最好的语言
php是最好的语言Original
2018-08-10 09:55:023988browse

Use regular expressions to remove English from strings

String str = "111,aaa,222,bbb";
Pattern p = Pattern.compile("[a-zA-z]");//创建stringBuff用来拼接StringBuffer sb = new StringBuffer();
String[] s = str .split(",");for (int i = 0; i < s.length; i++) {    //如果包含英文字母我这边不做处理,如果有需求,可以自己添加
    if(p.matcher(s[i]).find()) {    //不包含英文字母
    }else{        //拼接成新的字符串,判断当前索引如果不是最后一个,就在拼接完字符串以后加上 ","
        if(i < s.length - 1){
            sb.append(s[i] + ",");
        }else {            //如果是最后一个,就直接添加
            sb.append(s[i]);
        }
    }
}        //校验最后一位是否包含 ","  出现此情况的原因是:最后一位字符包含英文,我没有处理,倒数第二位字符在拼接的时候,因为不是最后一位,所以会加一个","
        String sbs = sb.toString();        if(sbs.endsWith(",")){
            sbs = sbs.substring(0,sbs.length() - 1);
        }
        System.out.println(sbs);

Output results:

111,222

Related recommendations:

How to remove various symbols between strings in Java

Java regular multi-string matching and replacement

The above is the detailed content of Java uses regular expressions to remove English from strings. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn