0

I want to act on markdown strings depending on whether they start with one, two or no #, but I am failing to rule ## out for being recognized as a title:

let strings = ["# Fancy Title", "## Fancy Subtitle", "Body Content")
for string in strings {
  if string.contains(/^#(^#)/) { //string should only contain **one** #, but `strings[0]` falls through now …
    // parse title
  } else if string.contains(/^##/) {
    // parse subtitle
  } else {
    // parse body
  }
}

How do I properly exclude ## in my first if stmt?

appfrosch
  • 1,146
  • 13
  • 36

2 Answers2

1
if string.contains(/^#[^#]/) {
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
Michi
  • 37
  • 4
1

You want to check for # followed by anything that isn't another #. That would be:

/^#[^#]/

You wanted square brackets, not parentheses.


There's really no need for the regular expressions. You could use:

if string.hasPrefix("##") {
    // parse subtitle
} else if string.hasPrefix("#") {
    // parse title
} else {
    // parse body
}

Note that you want to check for ## before you check for #.

Or with simpler regular expressions:

if string.contains(/^##/) {
    // parse subtitle
} else if string.contains(/^#/) {
    // parse title
} else {
    // parse body
}
HangarRash
  • 7,314
  • 5
  • 5
  • 32
  • Funny enough, `/^#[^#]/` does not work as expected–but you are right in pointing out that `.hasPrefix` is the much better approach in my use case. Thanks – appfrosch Aug 06 '23 at 07:25
  • @appfrosch `/^#[^#]/` does work. I tested it using your exact code with that small change and it gives the desired result. But the other solutions are simpler. – HangarRash Aug 06 '23 at 17:02