I am trying to search for a String inside a file content which I got into a String.
我试图在文件内容中搜索一个String,我将其放入String中。
I've tried to use Pattern
and Matcher
, which worked for this case:
我试过使用Pattern和Matcher,它适用于这种情况:
Pattern p = Pattern.compile("(</machine>)");
Matcher m = p.matcher(text);
while(m.find()) //if the text "(</machine>)" was found, enter
{
Counter++;
}
return Counter;
Then, I tried to use the same code to find how many tags I have:
然后,我尝试使用相同的代码来查找我有多少标签:
Pattern tagsP = Pattern.compile("(</");
Matcher tagsM = tagsP.matcher(text);
while(tagsM.find()) //if the text "(</" was found, enter
{
CounterTags++;
}
return CounterTags;
which in this case, the return value was always 0.
在这种情况下,返回值始终为0。
2 个解决方案
#1
5
Try using the below code , btw not using 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);
Output :- 4
输出: - 4
#2
3
You can use Apache commons-lang
util library, there is a function countMatches exactly for you:
您可以使用Apache commons-lang util库,完全有一个函数countMatches:
int count = StringUtils.countMatches(text, "substring");
Also this function is null-safe. I recommend you to explore Apache commons libraries, they provide a lot of useful common util methods.
此函数也是null安全的。我建议你去探索Apache commons库,它们提供了很多有用的常用util方法。
#1
5
Try using the below code , btw not using 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);
Output :- 4
输出: - 4
#2
3
You can use Apache commons-lang
util library, there is a function countMatches exactly for you:
您可以使用Apache commons-lang util库,完全有一个函数countMatches:
int count = StringUtils.countMatches(text, "substring");
Also this function is null-safe. I recommend you to explore Apache commons libraries, they provide a lot of useful common util methods.
此函数也是null安全的。我建议你去探索Apache commons库,它们提供了很多有用的常用util方法。