Home > Java > javaTutorial > body text

How to Split a String on Spaces While Preserving Quoted Substrings in Java?

Susan Sarandon
Release: 2024-11-11 13:49:02
Original
991 people have browsed it

How to Split a String on Spaces While Preserving Quoted Substrings in Java?

Splitting Strings on Spaces, Preserving Quoted Substrings in Java

Splitting a string on spaces can be straightforward, but it becomes more complex when quoted substrings need to be treated as a single token. Let's explore how to achieve this in Java.

Problem Statement:

How can we split the following string on spaces, considering that quoted substrings remain as one unit?

Location "Welcome to india" Bangalore Channai "IT city" Mysore
Copy after login

The desired output should be stored in an array list, preserving the quoted substrings:

[Location, "Welcome to india", Bangalore, Channai, "IT city", Mysore]
Copy after login

Solution:

By utilizing regular expressions, we can define a pattern that matches substrings that are either non-space characters ("1S") or quoted substrings (""(. ?)""). The pattern further allows for optional whitespace characters ("s") following the matches.

String str = "Location \"Welcome  to india\" Bangalore " +
             "Channai \"IT city\"  Mysore";

List<String> list = new ArrayList<>();
Matcher m = Pattern.compile("([^\"]\S*|\".+?\")\s*").matcher(str);
while (m.find())
    list.add(m.group(1)); // Add .replace("\"", "") to remove surrounding quotes.

System.out.println(list);
Copy after login

In this solution:

  • The pattern is compiled and used to match tokens in the string.
  • Matched tokens are added to the array list.
  • Optional removal of surrounding quotes can be achieved by using .replace(""", "") after adding tokens to the list.

Output:

[Location, "Welcome  to india", Bangalore, Channai, "IT city", Mysore]
Copy after login

  1. "

The above is the detailed content of How to Split a String on Spaces While Preserving Quoted Substrings in Java?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template