Home > Java > javaTutorial > How to Split Strings by Spaces While Preserving Quoted Sections Using Regex?

How to Split Strings by Spaces While Preserving Quoted Sections Using Regex?

Susan Sarandon
Release: 2024-12-15 13:22:15
Original
374 people have browsed it

How to Split Strings by Spaces While Preserving Quoted Sections Using Regex?

Splitting Strings Using Spaces When Not Surrounded by Quotes with Regex

In regular expression, it's possible to split a string using spaces while retaining spaces within quoted sections. Here's how to achieve this:

To address the issue in your original expression, (?!"), which splits on spaces before quotes, consider the following regular expression:

[^\s"']+|"([^"]*)"|'([^']*)'
Copy after login

This expression captures three patterns:

  1. 1 : Matches one or more non-whitespace, non-quote characters.
  2. "(2*)": Matches a double-quoted string, capturing the string without quotes in group 1.
  3. '(3*)': Matches a single-quoted string, capturing the string without quotes in group 2.

To split the string, you can use Java code like this:

List<String> matchList = new ArrayList<>();
Pattern regex = Pattern.compile("[^\s\"']+|\"([^\"]*)\"|'([^']*)'");
Matcher regexMatcher = regex.matcher(subjectString);
while (regexMatcher.find()) {
    if (regexMatcher.group(1) != null) {
        // Add double-quoted string without the quotes
        matchList.add(regexMatcher.group(1));
    } else if (regexMatcher.group(2) != null) {
        // Add single-quoted string without the quotes
        matchList.add(regexMatcher.group(2));
    } else {
        // Add unquoted word
        matchList.add(regexMatcher.group());
    }
}
Copy after login

This code builds a list of strings, stripping quotes from quoted words and preserving spaces within them.


  1. s"'
  2. "
  3. '

The above is the detailed content of How to Split Strings by Spaces While Preserving Quoted Sections Using Regex?. 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