【问题标题】:Look for a certain String inside another and count how many times it appears在另一个字符串中查找某个字符串并计算它出现的次数
【发布时间】:2015-10-08 13:52:33
【问题描述】:

我正在尝试在一个文件内容中搜索一个字符串,我输入了一个字符串。

我尝试使用 PatternMatcher,这适用于这种情况:

Pattern p = Pattern.compile("(</machine>)");
Matcher m = p.matcher(text);
while(m.find()) //if the text "(</machine>)" was found, enter
{
    Counter++;
}

return Counter;

然后,我尝试使用相同的代码来查找我有多少个标签:

Pattern tagsP = Pattern.compile("(</");
Matcher tagsM = tagsP.matcher(text);
while(tagsM.find()) //if the text "(</" was found, enter
{
    CounterTags++;
}

return CounterTags;

在这种情况下,返回值始终为 0。

【问题讨论】:

  • 为什么不起作用?它是否给了您误报,匹配没有()&lt;/machine&gt;
  • 我正在使用的文件是一个 xml 文件。我上传的代码是我的代码的旧版本,所以当我试图找到 () 字符串时,它可以工作,但是当我试图只找到 '(' 字符串来查看我有多少标签时有,结果总是0。
  • 您要查找文字字符串(&lt;/machine&gt;),还是只查找&lt;/machine&gt;?如果是前者,Ankit的答案中的代码不起作用。
  • 两者都可以。在我的xml文件中它会,但是当文件中的文本可以只是&lt;/machine&gt;时它不会,所以“更多”正确的选项是(&lt;/machine&gt;)
  • 请编辑您的问题以阐明您的要求。请务必包含非工作案例和示例输入。

标签: java regex string matcher


【解决方案1】:

尝试使用下面的代码,顺便说一句,不要使用Pattern:-

String actualString = "hello hi how(</machine>) are you doing. Again hi (</machine>) friend (</machine>) hope you are (</machine>)doing good.";
//actualString which you get from file content
String toMatch = Pattern.quote("(</machine>)");// for coverting to regex literal
int count = actualString .split(toMatch, -1).length - 1; // split the actualString to array based on toMatch , so final match count should be -1 than array length.
System.out.println(count);

输出 :- 4

【讨论】:

  • 您的代码将toMatch 传递给split() 函数,该函数需要一个正则表达式。如果输入字符串包含正则表达式语法中的元字符,这将导致问题。另一件事是split() 默认情况下会删除数组末尾的空字符串,这对于pppppaapp 这样的字符串在被p 分割时会给出不正确的结果。您需要调用split(regex, -1) 以保留最后的空字符串。
  • @nhahtdh 感谢提及,并补充说。向像你这样的人学习总是好的 :)
  • 您可能希望使用Pattern.quote 转义toMatch 中的正则表达式元字符,因为OP 已经阐明了要求。
  • 当我使用 Pattern.quote 时,出现运行时错误
  • 您的搜索模式是否与(&lt;/machine&gt;)@almogeinstein 相同
【解决方案2】:

您可以使用 Apache commons-lang util 库,有一个函数 countMatches 完全适合您:

int count = StringUtils.countMatches(text, "substring");

这个函数也是空安全的。 我建议你去探索Apache commons 库,它们提供了很多有用的常用 util 方法。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2011-07-01
  • 2011-07-13
  • 1970-01-01
  • 2017-10-09
  • 2010-11-12
  • 1970-01-01
相关资源
最近更新 更多