匹配模式在 match.find 时忽略源中的空白

问题描述 投票:0回答:1

我有一个图案

String pageText="Hello World, How areyou doing"
(没有空间)。并进行搜索
pattern
代表
"How are you"

Matcher matcher = pattern.matcher(pageText));
int count = 0;
while (matcher.find()) {
  count++;
}

counter
正在返回
0
,因为我的
pageText
变量中缺少空格。

有没有办法忽略空格检查,并且应该能够找到模式“How are you”的匹配项?

java regex whitespace
1个回答
0
投票

最简单的方法之一可能是在正则表达式模式中用

\s*
替换空格,这样它看起来更像
"How\\s*are\\s*you"
,这样它就可以匹配
Howareyou
How areyou
Howare you

String pageText="Hello World, How areyou doing";

Pattern pattern = Pattern.compile("How are you".replaceAll("\\s+","\\\\s*"));

Matcher matcher = pattern.matcher(pageText);
int count = 0;
while (matcher.find()) {
  count++;
}

System.out.println(count);

编辑:

由于您使用

Pattern.quote
来转义所有正则表达式特殊字符,因此在内部添加
\s*
没有多大意义,因为它也会被转义。简单的解决方案是仅引用单词,因为只有它们可以具有需要转义的正则表达式元字符,因此我们正在寻找解决方案,它将为我们构建类似

的内容
quote(word1)\s*quote(word2)\s*quote(word3)

代码如下所示:

String pageText = "Hello World, How areyou doing";
String searchFor = "How are you";

String searchingRegex = Stream.of(searchFor.split("\\s+"))//stream of words
        .map(word -> Pattern.quote(word))//quote each word
        .collect(Collectors.joining("\\s*"));//join words with `\s*` delimiter

Pattern pattern = Pattern.compile(searchingRegex);
//...
© www.soinside.com 2019 - 2024. All rights reserved.