'Algo to check that a string doesn't have missing close quote ( ', " OR ` )

What is the best way to check in python that given a string, there are no open quotes in it?

e.g.

// missing quote
bar, fun("foo"), "zaa 

// OK quote
bar, fun("foo), "zaa 

// missing quote
bar, fun("foo), zaa 


// ok quote (single quote encompasses both ends)
bar', fun("foo), zaa' 


// ok quote since there is the escape
bar', \'fun("foo), zaa' 

// missing quote since there is the escape
bar', \'fun("foo), zaa 

// missing quote
bar', fun("foo"), zaa 

I was trying to run something like

regexp(raw, '"(^".*?)"', my_string)
regexp(raw, '`(^`.*?)`', my_string)
regexp(raw, '\'(^\'.*?)\'', my_string)

but this detects only if the string was correctly closed

This was another attempt, but I'm still trying to come up with a clear logic to detect that all of the previous quotes were already closed

regexp(raw, '"(^".*?)$', my_string)


Solution 1:[1]

You may not use regex, just use stack to check it. This problem is sort of correct bracket checking problem.

UPD: update quote characters

UPD2: regex is not a perfect tool for this case.

def is_quote_ok(s):
    stack = []
    for c in s:
        if c in ["'", '"', "`"]:
            if stack and stack[-1] == c:
                # this single-quote is close character
                stack.pop()
            else:
                # a new quote started
                stack.append(c)
        else:
            # ignore it
            pass

    return len(stack) == 0

Solution 2:[2]

Let's break this problem down:

(1) There is always only one "open" quote.

(2) At the end of the string there must be no open quote.

(3) A quote-symbol that follows the escape-symbol does not open or close a quote.

Solution:

  • Create a variable that saves what kind of quote is currently opened and initialize it with the empty string
  • Iterate over the letters
  • If there is an escape-symbol, skip the next letter
  • If there is quote symbol and currently_open is the empty string, change currently_open to the quote symbol
  • If there is a quote symbol and currently_open matches the quote-symbol, change currently_open to the empty string
  • If there is a quote symbol and currently_open contains another kind of quoute-symbol, do nothing
  • If at the end of the string currently_open matches the empty string, answer with true, else with false

That's it, have fun.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2