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!