Java 分词模糊查询 正则表达式匹配字符串
时间: 2023-10-13 15:05:49 浏览: 61
Java 分词模糊查询可以使用 Lucene 或者 Elasticsearch 等全文检索引擎实现,也可以使用传统的模糊匹配算法,如编辑距离算法、通配符匹配、正则表达式等。
下面是一个使用正则表达式匹配字符串的例子:
```java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
public static void main(String[] args) {
String text = "hello world, hello java, hello python";
String patternString = "hello \\w+"; // 匹配 hello 后面跟一个或多个字母、数字、下划线
Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
System.out.println("Match found: " + matcher.group());
}
}
}
```
输出结果为:
```
Match found: hello world
Match found: hello java
Match found: hello python
```
在上面的例子中,我们使用了 `\w+` 匹配一个或多个字母、数字、下划线。如果想要匹配任意字符,可以使用 `.`。如果想要匹配多个字符,可以使用 `{n,m}` 表示匹配长度为 n 到 m 的字符串,如 `\w{3,5}` 表示匹配长度为 3 到 5 的字母、数字、下划线。