String正则表达式
时间: 2023-08-24 10:04:51 浏览: 53
正则表达式是一种用于匹配和操作字符串的强大工具。在Java中,可以使用String类的matches()方法来进行正则表达式的匹配。
下面是一些常见的String正则表达式示例:
1. 匹配数字:
```java
String regex = "\\d+";
String str = "12345";
boolean isMatched = str.matches(regex);
System.out.println(isMatched); // 输出 true
```
2. 匹配字母:
```java
String regex = "[a-zA-Z]+";
String str = "Hello";
boolean isMatched = str.matches(regex);
System.out.println(isMatched); // 输出 true
```
3. 匹配邮箱:
```java
String regex = "\\w+@\\w+\\.\\w+";
String str = "example@example.com";
boolean isMatched = str.matches(regex);
System.out.println(isMatched); // 输出 true
```
4. 匹配手机号码(简化版):
```java
String regex = "1\\d{10}";
String str = "13812345678";
boolean isMatched = str.matches(regex);
System.out.println(isMatched); // 输出 true
```
需要注意的是,在Java中使用正则表达式时,需要使用双反斜杠(\\)来转义特殊字符。
除了matches()方法外,还可以使用Pattern和Matcher类来进行更复杂的正则表达式操作。这些类提供了更多的灵活性和功能,可以用于匹配、查找、替换等操作。