Home >Java >javaTutorial >How to Split Strings with Spaces Inside Quotes Using Regular Expressions?
Regex for Splitting Strings: Ignoring Spaces Within Quotes
Identifying spaces for string splitting can be challenging when those spaces are enclosed within single or double quotes. To address this, consider the following regular expression:
[^\s"']+|\"([^\"]*)"|'([^']*)'
This expression separates the string into two types of patterns:
Java Implementation:
The following Java code uses this regular expression to split the string:
List<String> matchList = new ArrayList<>(); Pattern regex = Pattern.compile("[^\s\"']+|\"([^\"]*)"|'([^']*)'"); Matcher regexMatcher = regex.matcher(subjectString); while (regexMatcher.find()) { if (regexMatcher.group(1) != null) { matchList.add(regexMatcher.group(1)); // Double-quoted string } else if (regexMatcher.group(2) != null) { matchList.add(regexMatcher.group(2)); // Single-quoted string } else { matchList.add(regexMatcher.group()); // Unquoted word } }
Simpler Option:
If maintaining quotes in the returned list is acceptable, a simpler version of the code is possible:
List<String> matchList = new ArrayList<>(); Pattern regex = Pattern.compile("[^\s\"']+|\"[^\"]*\"|'[^']*'"); Matcher regexMatcher = regex.matcher(subjectString); while (regexMatcher.find()) { matchList.add(regexMatcher.group()); }
This approach is less complex but includes quotes in the returned list elements.
The above is the detailed content of How to Split Strings with Spaces Inside Quotes Using Regular Expressions?. For more information, please follow other related articles on the PHP Chinese website!