Java怎么用正则表达式过滤出字母、数字和中文
正则表达式是一种强大的文本匹配工具,可以用来进行字符串的模式匹配与检索。在Java中,可以使用正则表达式过滤出字母、数字和中文。下面将分为三个段落介绍如何使用正则表达式来实现。
1. 过滤字母
使用正则表达式来过滤字母可以使用字符类(character class)来匹配大写字母和小写字母。其中,表达式[a-zA-Z]可以匹配任意大小写的字母。
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String input = "abc123ABC中文";
String regex = "[a-zA-Z]+";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
System.out.println(matcher.group());
}
}
}
上述代码输出结果为:
abc ABC
2. 过滤数字
使用正则表达式过滤数字可以使用字符类\d来匹配数字。字符类\d等价于[0-9],可以匹配任意一个数字。
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String input = "abc123ABC中文";
String regex = "\\d+";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
System.out.println(matcher.group());
}
}
}
上述代码输出结果为:
123
3. 过滤中文
使用正则表达式过滤中文可以使用Unicode编码来匹配中文字符。中文字符的Unicode编码范围为\u4e00-\u9fa5。
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String input = "abc123ABC中文";
String regex = "[\\u4e00-\\u9fa5]+";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
System.out.println(matcher.group());
}
}
}
上述代码输出结果为:
中文
综上所述,使用正则表达式可以过滤出字母、数字和中文。对于字母可以使用字符类[a-zA-Z],对于数字可以使用字符类\d,对于中文可以使用Unicode编码范围[\u4e00-\u9fa5]来匹配。
猜您想看
-
如何处理电脑上的系统崩溃?
电脑系统崩溃是...
2023年04月24日 -
Python爬取世纪佳缘的数据是否能证明它不靠谱的示例分析
Python爬...
2023年07月22日 -
Python+appium框架原生代码实现App自动化测试的示例分析
1. Pyth...
2023年05月26日 -
在Windows上如何设置计算机睡眠和唤醒
如何设置Win...
2023年04月27日 -
如何在CS:GO游戏中控制结构和耐久度?
如何在CS:G...
2023年04月17日 -
如何在宝塔面板中配置CDN加速?
如何使用宝塔面...
2023年04月16日