java正则表达式匹配精准单词
时间: 2023-07-05 15:28:31 浏览: 57
要精准地匹配一个单词,可以使用`\b`边界。`\b`匹配单词边界,即单词字符(字母、数字、下划线)与非单词字符(其他字符)之间的位置。例如,要匹配单词"hello",可以使用正则表达式`\bhello\b`。这样就只会匹配"hello"这个单词,而不会匹配到"helloo"或者"ahello"等词。在Java中,可以使用`Pattern`和`Matcher`类来进行正则表达式的匹配。以下是一个示例代码:
```java
String text = "hello world, helloo, ahello";
String pattern = "\\bhello\\b";
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(text);
while (m.find()) {
System.out.println("Match: " + m.group(0));
}
```
这段代码会输出:
```
Match: hello
```
可以看到,只有"hello"这个单词被匹配到了。
相关问题
Java 正则表达式 匹配整个单词
你可以使用 `\b`(单词边界)来匹配整个单词。以下是一个示例的 Java 代码:
```java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String text = "Hello, world! This is a test.";
String pattern = "\\btest\\b";
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(text);
while (m.find()) {
System.out.println("Match: " + m.group());
}
}
}
```
在这个例子中,我们使用正则表达式 `\btest\b` 来匹配整个单词 "test"。运行代码后,你将会看到输出结果为 "Match: test"。
这里的 `\b` 是一个特殊的元字符,用于匹配单词的边界。它匹配一个位置,这个位置既不在一个单词的内部,也不在单词的外部。
java 正则表达式匹配
Java正则表达式匹配可以使用java.util.regex类。常见的用法是使用Pattern匹配器构造一个正则表达式,然后使用该正则表达式进行字符串匹配。例如,以下代码可以判断一个字符串是否为手机号:
```java
String regex = "^1[34578]\\d{9}$"; // 手机号正则表达式
Pattern pattern = Pattern.compile(regex);
String phoneNumber = "13912345678"; // 待匹配的手机号
boolean isMatched = pattern.matcher(phoneNumber).matches();
System.out.println(isMatched); // true
```
这里的正则表达式是"^1[34578]\\d{9}$",表示以1开头,后跟3、4、5、7、8中的一个数字,并且后面跟着9个数字,这个正则表达式可以匹配符合规则的手机号。
注意,特殊字符需要转义,比如"\\d"匹配数字,"\\s"匹配空白字符,"\\w"匹配字母、数字、下划线等,而"\\."匹配句点本身。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)