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"']+|"([^"]*)"|'([^']*)'
This expression captures three patterns:
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()); } }
This code builds a list of strings, stripping quotes from quoted words and preserving spaces within them.
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!