Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Find word in a String

Tags:

java

regex

I need to find a word in a HTML source code. Also I need to count occurrence. I am trying to use regular expression. But it says 0 match found.

I am using regular expression as I thought its the best way. In case of any better way, please let me know.

I need to find the occurrence of the word "hsw.ads" in HTML source code.

I have taken following steps.

int count = 0;
{
    Pattern p = Pattern.compile(".*(hsw.ads).*");
    Matcher m = p.matcher(SourceCode);
    while(m.find())count++;
}

But the count is 0;

Please let me know your solutions.

Thank you. Help Seeker

like image 384
Help seeker Avatar asked Mar 14 '26 05:03

Help seeker


1 Answers

You are not matching any "expression", so probably a simple string search would be better. commons-lang has StringUtils.countMatches(source, "yourword").

If you don't want to include commons-lang, you can write that manually. Simply use source.indexOf("yourword", x) multiple times, each time supplying a greater value of x (which is the offset), until it gets -1

like image 61
Bozho Avatar answered Mar 16 '26 17:03

Bozho



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!