import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = "^Q: ((?:.*|\\n)*?)\\n*A: (.+(?:\\n(?:^.{1,3}$|^.{4}(?<!<!--).*))*)\n";
final String string = "Q: diff between null and undefined?\n\n"
+ "A: Null indicates an intentional empty value. \n"
+ "- Undefined indicates the total absence of a value. This happen when only the variable was declared without any initializer. A missing key in an object is also undefined. \n"
+ "```javascript\n"
+ "export function ticketStatus(tickets, ticketId) {\n"
+ " if (tickets[ticketId] === undefined) {\n"
+ " return 'unknown ticket id';\n"
+ " } else if (tickets[ticketId] === null) {\n"
+ " return 'not sold';\n"
+ " } else {\n\n"
+ " return `sold to ${tickets[ticketId]}`;\n"
+ " }\n"
+ "}\n"
+ "```\n"
+ "<!--ID: 1673953179724-->\n\n\n"
+ "---\n"
+ "Q: rewrite to use [[JS Object.assign]]\n"
+ "```javascript\n"
+ "visitor.ticketId = null;\n\n"
+ "return visitor;\n"
+ "```\n\n\n"
+ "A: Just pass only the props we want to overwrite to assign\n"
+ "```javascript\n"
+ "return Object.assign(visitor, {ticketId: null});\n"
+ "```\n"
+ "<!--ID: 1673953179746-->\n\n\n"
+ "---\n\n"
+ "Q: diff between isNaN() global vs Number.isNaN()?\n\n"
+ "A: global isNaN() does type conversion. \n"
+ "- Since I am trying to test whether the string contains a valid number, this is the right choice. \n"
+ "- If the input is already a number, then Number.isNaN() might be better. as\n\n"
+ "---\n";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println("Full match: " + matcher.group(0));
for (int i = 1; i <= matcher.groupCount(); i++) {
System.out.println("Group " + i + ": " + matcher.group(i));
}
}
}
}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Java, please visit: https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html