I started writing this algorithm:
public static String convert(String str) {
if (str.equals("# "))
return " ";
if (str.matches("#+.+")) {
int n = str.length() - str.replaceFirst("#+", "").length();
return "<h" + n + ">" + str.substring(n) + "<h" + n + ">";
}
return str;
}
}
So when I type, ####title, it returns < h4>title< /h4>
My problem is that when I write ####title###title, I would like it to return < h4>title< /h4> < h3>title< /h3> but it only returns < h4>title< /h4>…What am I doing wrong???
Thats because you are using the pattern: –
#+.+.Now, since
.matches everything in Regex, so in the above pattern, it matcheseverythingafter aninitial setof#'s.So, for your input: – ####title###title, your pattern will match: –
#+will match####.+will matchtitle###titleYou need to change your regex to : –
(#+[^#]+), and probably need to use Pattern class here to get the desired output, becaues you want to matcheverypart of your string to the givenpattern.#+[^#]+-> Will match the first set of#and then everything after that, except#. So it stops where the next set of#'sstart.Here’s how you can use it: –
OUTPUT: –