I have a string with markdown syntax in it, and I want to be able to find markdown syntax for headings, i.e h1 = #, h2 = ## etc etc.
I know that whenever I find a heading, it is at the start of the line. I also know there can only be one heading per line. So for example, "###This is a heading" would match true for my h3 pattern, but not for my h2 or h1 patterns. This is my code so far:
h1 = Pattern.compile("(?<!\\#)^\\#(\\b)*");
h2 = Pattern.compile("(?<!\\#)^\\#{2}(\\b)*");
h3 = Pattern.compile("(?<!\\#)^\\#{3}(\\b)*");
h4 = Pattern.compile("(?<!\\#)^\\#{4}(\\b)*");
h5 = Pattern.compile("(?<!\\#)^\\#{5}(\\b)*");
h6 = Pattern.compile("(?<!\\#)^\\#{6}(\\b)*");
Whenever I use \\#, my compiler (IntelliJ) tells me: "Redundant character escape". It does that whenever I use \\#. As far as I know, # should not be a special character in regex, so escaping it with two backslashes should allow me to use it.
When I find a match, I want to surrond the entire match with bold HTML-tags, like this: "###Heading", but for some reason it's not working
//check for heading 6
Matcher match = h6.matcher(tmp);
StringBuffer sb = new StringBuffer();
while (match.find()) {
match.appendReplacement(sb, "<b>" + match.group(0) + "</b>");
}
match.appendTail(sb);
tmp = sb.toString();
EDIT
So I have to seperately look at each heading, I can't look at heading 1-6 in the same pattern (this has to do with other parts of my program that uses the same pattern). What I know so far:
- If there is a heading in the string, it is at the start.
- If it starts with a heading, the entire string that follows is considered a heading, until the user presses Enter.
- If I have "## This a heading", then it must match true for h2, but false for h1.
- When I find my match, this "## This a heading" becomes this "## This a heading.
#
. You do not even need theMatcher#appendReplacement
here. You may use"(?<!#)#{6}\\b"
, and then use a simpletmp = tmp.replaceAll("(?<!#)#{6}\\b", "<b>$0</b>")
– Prenatal#
sequences, see my updated answer. Always add new details to the question itself, and not to just comments. – Prenatal