1

I have a String replacedtext which is:

Replaced text:OPTIONS (ERRORS=5000)
LOAD DATA
INFILE *
APPEND INTO TABLE REPO.test
Fields terminated by "," optionally enclosed BY '"'
trailing nullcols
(
CODE ,
user,
date DATE "MM/DD/YYYY"
)

I want to count the Number of REPO. in this whole string.So,I tried in this way but it is not working.

String[] words = replacedtext.split("\\s+");
        int count=0;
       for(String w:words){​​​​​​​
           if(w.equals("\\bREPO.\\b")){​​​​​​​
               count++;
           }​​​​​​​
       }​​​​​​​
System.out.println ("count is :"+count);

Output coming is:

count is :0

Since in the string REPO. is seen for once. My output needs to be count is:1.

2 Answers2

2

w.equals("\\bREPO.\\b") compares the content of w with \\bREPO.\\b literally and therefore you are getting a wrong result.

You can count the occurrences of REPO using the regex API.

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) {
        String replacedText = """
                Replaced text:OPTIONS (ERRORS=5000)
                LOAD DATA
                INFILE *
                APPEND INTO TABLE REPO.test
                Fields terminated by "," optionally enclosed BY '"'
                trailing nullcols
                (
                CODE ,
                user,
                date DATE "MM/DD/YYYY"
                )
                """;

        Matcher matcher = Pattern.compile("\\bREPO\\b").matcher(replacedText);

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

        System.out.println(count);
    }
}

Output:

1

Note that \b is used as word boundary matcher.

Java SE 9 onwards, you can use Matcher#results to get a Stream on which you can call count as shown below:

long count = matcher.results().count();

Note: I've used Text Block feature to make the text block look more readable. You can form the string in the Pre-Java15 way.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
0

Probably 2 issues here. . is a special symbol which represents exactly one character. So your REPO.test won't match.

The second issue is equals method. You should use matcher or just filter by regex and then count.

I would do it so:

int count = Pattern.compile("\\s").splitAsStream(replacedtext)
    .filter(Pattern.compile("\\bREPO\\b").asPredicate())
    .count()
System.out.println(count);
Eduard Dubilyer
  • 991
  • 2
  • 10
  • 21