BreakIterator Word And Sentence Boundaries

Split text into words and sentences at locale-correct boundaries with BreakIterator, so apostrophes, decimals like 2.5, and abbreviations stay one token.

JavaData Integrity

Code

snippet
import java.text.BreakIterator;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class TicketNotes {

    public static void main(String[] args) {
        String text = "Password reset failed twice. Don't retry after 2.5 minutes!";

        BreakIterator words = BreakIterator.getWordInstance(Locale.US);
        words.setText(text);
        System.out.println("word boundaries: " + tokensOf(words, text));

        BreakIterator sentences = BreakIterator.getSentenceInstance(Locale.US);
        sentences.setText(text);
        System.out.println("sentence boundaries: " + tokensOf(sentences, text));
    }

    // next() 逐个给出边界偏移,DONE 表示遍历结束
    private static List<String> tokensOf(BreakIterator iterator, String text) {
        List<String> tokens = new ArrayList<>();
        int start = iterator.first();
        for (int end = iterator.next(); end != BreakIterator.DONE; start = end, end = iterator.next()) {
            String piece = text.substring(start, end);
            if (!piece.isBlank()) {
                tokens.add(piece);
            }
        }
        return tokens;
    }
}

How the snippet works

The working surface is the class TicketNotes and the functions main and tokensOf — everything else is wiring.

Repetition is confined to for (int end = iterator.next(); end != BreakIterator.DONE; start = end, end = iterator.next()) — the rest of the file is straight-line.

Applying it

Running the file prints labeled results such as word boundaries:, sentence boundaries: — each operation’s effect is visible in the output.

The demo flow inside main is tokensOf — run the file to see it end to end.

Statements that matter

String text = "Password reset failed twice. Don't retry after 2.5 minutes!";
BreakIterator sentences = BreakIterator.getSentenceInstance(Locale.US);
BreakIterator words = BreakIterator.getWordInstance(Locale.US);

Interactive Tools for This Topic

FAQ

What does BreakIterator Word And Sentence Boundaries print when run?
Running the file directly is enough — expect labeled output lines such as `word boundaries:`, `sentence boundaries:`.