in TextStyling/app/src/main/java/com/android/example/text/styling/parser/Parser.java [109:165]
private static List<Element> findElements(@NonNull final String string,
@NonNull final Pattern pattern) {
List<Element> parents = new ArrayList<>();
Matcher matcher = pattern.matcher(string);
int lastStartIndex = 0;
while (matcher.find(lastStartIndex)) {
int startIndex = matcher.start();
int endIndex = matcher.end();
// we found a mark
String mark = string.substring(startIndex, endIndex);
if (lastStartIndex < startIndex) {
// check what was before the mark
parents.addAll(findElements(string.substring(lastStartIndex, startIndex), pattern));
}
String text;
// check what kind of mark this was
switch (mark) {
case BULLET_PLUS:
case BULLET_STAR:
// every bullet point is max until a new line or end of text
int endOfBulletPoint = getEndOfParagraph(string, endIndex);
text = string.substring(endIndex, endOfBulletPoint);
lastStartIndex = endOfBulletPoint;
// also see what else we have in the text
List<Element> subMarks = findElements(text, pattern);
Element bulletPoint = new Element(Type.BULLET_POINT, text, subMarks);
parents.add(bulletPoint);
break;
case CODE_BLOCK:
// a code block is set between two "`" so look for the other one
// if another "`" is not found, then this is not a code block
int markEnd = string.indexOf(CODE_BLOCK, endIndex);
if (markEnd == -1) {
// we don't have an end of code block so this is just text
markEnd = string.length();
text = string.substring(startIndex, markEnd);
parents.add(new Element(Type.TEXT, text, Collections.<Element>emptyList()));
lastStartIndex = markEnd;
} else {
// we found the end of the code block
text = string.substring(endIndex, markEnd);
parents.add(new Element(Type.CODE_BLOCK, text,
Collections.<Element>emptyList()));
// adding 1 so we can ignore the ending "`" for the code block
lastStartIndex = markEnd + 1;
}
break;
}
}
// check if there's any more text left
if (lastStartIndex < string.length()) {
String text = string.substring(lastStartIndex, string.length());
parents.add(new Element(Type.TEXT, text, Collections.<Element>emptyList()));
}
return parents;
}