Last active
November 24, 2017 19:40
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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