Search code examples
swiftswift-regexbuilder

Problems creating regex for not containing character


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?


Solution

  • 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
    }