Java如何計數位串中的一組詞組?

2019-10-16 22:25:34

在Java程式設計中,如何在字串中搜尋指定的單詞(子字串)?

以下範例演示如何使用regex.Matcher類的matcher.start()方法來搜尋字串中的特定單詞。

package com.yiibai;

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

public class SearchingWord {
    public static void main(String args[]) {
        String patternString = "java";
        String candidateString = "This is a java program. This is another java program.";
        // Matcher matcher = p.matcher(candidateString);
        Pattern pattern = Pattern.compile(patternString);
        Matcher matcher = pattern.matcher(candidateString);
        int count = 0;
        while (matcher.find()) {
            count++;
            System.out.println("found: " + count + " : " + matcher.start() + " - " + matcher.end());
        }
    }
}

上述程式碼範例將產生以下結果 -

found: 1 : 10 - 14
found: 2 : 40 - 44

範例-2

以下是在字串中搜尋指定的單詞(子字串)的另一個範例。

package com.yiibai;

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

public class SearchingWord2 {
    public static void main(String[] args) {
        String s1 = "yiibai is one of best IT Yiibai website.";
        String regex = "\\btutorials\\b";
        Pattern p1 = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
        Matcher m1 = p1.matcher(s1);

        while (m1.find()) {
            System.out.print("Start index: " + m1.start());
            System.out.print(" End index: " + m1.end() + " ");
            System.out.println(m1.group());
        }
    }
}

上述程式碼範例將產生以下結果 -

Start index: 25 End index: 34 Yiibai