Skip to content

Instantly share code, notes, and snippets.

@caiofrota
Last active November 24, 2017 19:40
Show Gist options
  • Save caiofrota/9c3510cff288a4c4d9c626f97a238460 to your computer and use it in GitHub Desktop.
Save caiofrota/9c3510cff288a4c4d9c626f97a238460 to your computer and use it in GitHub Desktop.
Regex to extract strings separated by anything, ignoring the separator in double quotation marks.
Regex to extract strings separated by anything, ignoring the separator in double quotation marks.
("(.+)")|[^,]+ : Comma
("(.+)")|[^;]+ : Semicolon
("(.+)")|[^\.]+ : Dot
("(.+)")|[^\|]+ : Pipe
("(.+)")|[^\\]+ : Backslash
Explanation:
("(.+)") : Any string starting and ending with double quotation marks
| : or
[^,]+ : Any non-comma value
Sample in java:
/**
* Extract strings separated by anything, ignoring the separator in double quotation marks.
*
* @param text Full text.
* @param separatorRegex Separator.
* @param ignoreSeparatorInDoubleQuotes True to ignore the separator in double quotation marks.
* @return String array.
*/
public static String[] split(String text, String separatorRegex, boolean ignoreSeparatorInDoubleQuotes) {
String regex = "[^" + ((separatorRegex == null) ? ";" : separatorRegex) + "]+";
if (ignoreSeparatorInDoubleQuotes) {
regex = "(\"(.+)\")|" + regex;
}
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(text);
List<String> list = new ArrayList<String>();
while (matcher.find()) {
list.add(matcher.group());
}
return (String[]) list.toArray(new String[list.size()]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment