DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Migrate, Modernize and Build Java Web Apps on Azure: This live workshop will cover methods to enhance Java application development workflow.

Modern Digital Website Security: Prepare to face any form of malicious web activity and enable your sites to optimally serve your customers.

Kubernetes in the Enterprise: The latest expert insights on scaling, serverless, Kubernetes-powered AI, cluster security, FinOps, and more.

E-Commerce Development Essentials: Considering starting or working on an e-commerce business? Learn how to create a backend that scales.

Related

  • Navigating NoSQL: A Pragmatic Approach for Java Developers
  • Taming the Virtual Threads: Embracing Concurrency With Pitfall Avoidance
  • Java 11 to 21: A Visual Guide for Seamless Migration
  • Quarkus 3: The Future of Java Microservices With Virtual Threads and Beyond

Trending

  • A Comprehensive Guide to Cloud Monitoring Tools: Ensuring Optimal Performance and Security
  • The Future of Java: Virtual Threads in JDK 21 and Their Impact
  • What Is CI/CD? Beginner’s Guide To Continuous Integration and Deployments
  • Decompose Legacy System Into Microservices: Part 2
  1. DZone
  2. Coding
  3. Java
  4. Java Scanner: Text Parsing Made Easy

Java Scanner: Text Parsing Made Easy

Java's Scanner class, and the occasional bit of RegEx, makes parsing text trivial. You can put this to good use in a number of ways, which we'll dive into here.

Jay Sridhar user avatar by
Jay Sridhar
·
Feb. 22, 17 · Tutorial
Like (8)
Save
Tweet
Share
50.6K Views

Join the DZone community and get the full member experience.

Join For Free

“The only way of discovering the limits of the possible is to venture a little way past them into the impossible.”
― Arthur C. Clarke

Java provides a Scanner class that can be used as a text parser. It accepts a regular expression as a delimiter and returns tokens separated by the delimiter. Let us look at some usage scenarios of the Scanner class.

Image title


Count Words in a File

The default delimiter used by the Scanner is whitespace. It returns text tokens separated by whitespace. Let us use this fact to count the words in a file. The following code prints the value as well as its index from the file. Note that the Scanner implements the AutoCloseable interface so we can use it in try-with-resources block.

try (Scanner scanner = new Scanner(new File(filename));) {
    int nword = 0;
    while (scanner.hasNext()) {
    String sent = scanner.next();
    nword++;
    System.out.printf("%3d) %s%n", nword, sent);
    }
}


Read Text by Paragraph

Specifying an empty-line regex as the delimiter allows you to read text by paragraphs. The regular expression pattern specifies the multi-line flag, so use ^ and $ match at the beginning and end of each line, rather than the whole input.

try (Scanner scanner = new Scanner(new File(filename));) {
    scanner.useDelimiter("(?m:^$)");
    int ntoken = 0;
    while (scanner.hasNext()) {
    String token = scanner.next();
    ntoken++;
    System.out.printf("%3d) %s%n", ntoken, token);
    }
}


Scanner Trick: Read a Whole File

To read the whole file in a single String, use the following. The delimiter here is the regular expression for the beginning of the file.

try (Scanner scanner = new Scanner(new File(filename));) {
    scanner.useDelimiter("\\A");
    String all = scanner.next();
}


Summary

The Java class Scanner is used for text parsing. By setting the delimiter appropriately, various parsing tasks can be accomplished.

Java (programming language)

Published at DZone with permission of Jay Sridhar, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Navigating NoSQL: A Pragmatic Approach for Java Developers
  • Taming the Virtual Threads: Embracing Concurrency With Pitfall Avoidance
  • Java 11 to 21: A Visual Guide for Seamless Migration
  • Quarkus 3: The Future of Java Microservices With Virtual Threads and Beyond

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: